joi, 17 decembrie 2015

Using OmniFaces ResourceInclude and OutputFormat to display in a JSF page the decorated output from a Servlet/JSP

OmniFaces provides a component capable to  catch the output from a JSP or Servlet resource and render it as output to the JSF writer. For example, let's suppose that we have the following simple Servlet:

@WebServlet("/TextServlet")
public class TextServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  out.println("<h3>I'm a servlet that returns text ...</h3>");
 }

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  processRequest(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  processRequest(request, response);
 }
}

The OmniFaces component is named ResourceInclude and can be used via <o:resourceInclude/> tag as in the below example (output to the JSF writer the text output from TextServlet):

<o:resourceInclude path="/TextServlet" />


More examples and details about ResourceInclude are available in Mastering OmniFaces book.

Now, let's suppose that we want to modify (decorate) the Servlet output before we display it in page. A nice trick will consist in using another OmniFaces component named, OutputFormat. This component extends the standard <h:outputFormat/> with support for capturing the output and exposing it into the request scope by the variable name as specified by the var attribute. For example, we can capture the TextServlet output and expose it via <o:outputFormat/> as below:

<o:outputFormat var="_text">
 <o:resourceInclude path="/TextServlet" />
</o:outputFormat>

This time the TextServlet output is not displayed on screen. This output was stored in the request scope and it is available via _text anywhere in page. This means that we can pass this output to an action method which decorates it accordingly:

@Named
@RequestScoped
public class TextBean {

 public String decorate(String text) {
  return "***" + text + "***";
 }
}

<h:outputText value="#{textBean.decorate(_text)}" escape="false"/>


More examples and details about OutputFormat are available in Mastering OmniFaces book.

The complete application is available here.

Special thanks to Arjan Tijms for providing this tip.

Niciun comentariu:

Trimiteți un comentariu