Generate HTML page from a JSF backing Bean

Tuesday, 17 April 2012 14:02

Gernerate plain HTML using a Java Server faces backing bean

Generate plain HTML page using a backing bean

Sometimes you need to generate plain html or copy the content of a servlet response using a Backing Bean. This result can be achieved using the External Context provided by the FacesContext object. The external context object give you access to your servlet environment. We will use it to get access to the ServletResponse and write on it.

Let's take a simple page with a button calling our backing bean :

Java Server Faces button and form to call the html backing bean


<h:form>
    <h:commandButton  
        id="helloWorldButtonId"
        value="Print Hello World" 
        actionListener="#{helloBB.printHello}"/>
</h:form>

Our HelloBB backing bean should look like :

JSF 2 Backing bean render html using Servlet Response object


package sample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
@ManagedBean
public class HelloBB {
 
 public void printHello(){
  try {
   ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
   HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
   PrintWriter pw = response.getWriter();
   pw.write("<html>");
   pw.write("<h2>Hello World</h2>");
   pw.write("</html>");
   FacesContext.getCurrentInstance().responseComplete();  
  } catch (IOException e) {
   FacesContext.getCurrentInstance().addMessage(
     "helloWorldButtonId",
     new FacesMessage("Error:" + e.getMessage())
   );
  }
 }
}

The result should be a fantastic html page with the big Hello World�title

Tags: java , html , bean , page , server , generate , faces , backing

Add comment


Security code
Refresh