Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Web Development

Using JSF and JSR 168 Portals to Develop Ajax Applications


Integrating Ajax JSF Components Into Portals

We now review how JSF components are typically designed to handle asynchronous requests needed to deliver an Ajax behavior. For greater clarity, we base our explanations on the auto-suggest input field.

In the sample code below, the autoSuggest component has both a value attribute used for display and a suggestMethod attribute. It references a server-managed bean that computes all the suggested texts for the submitted keyword:

JSP page sample:

  <foo:autoSuggest value="initial value"
                 suggestMethod="#{myServerBean.getSuggestion}"/>

Server-managed bean sample:

public class MyServerBean {
  public String[] getSuggestion(String prefix) {
    // query the response somewhere and returns it
    return new String[] {};
  }
}

In addition to the HTML <<input> tag, this JSF component renders JavaScript code to perform asynchronous requests to the server as the user types using XmlHttpRequest calls. It then displays the server responses in the client browser.

The Ajax request to the server for suggestions contains an additional parameter, &autosuggest='value'. This request is processed by a JSF 1.2 PhaseListener instance registered on the server JSF life cycle by a faces-config.xml. It sends back the suggestions as JSON or XML data; see blueprints.dev.java.net/bpcatalog/ee5/ajax/phaselistener.html. The same Ajax request also contains the reference to the method referred to by the tag.

For instance, when users want to get suggestions for the keyword "start," the following PhaseListener is called via XmlHttpRequest:

public class AutoSuggestRequestHandler implements PhaseListener {
  private class Class[] PARAMS = new Class[] { String.class };

  public void afterPhase(PhaseEvent event) {
    FacesContext ctx = event.getFacesContext();
    HttpServletRequest request = (HttpServletResponse)
      ctx.getExternalContext().getRequest();
    Object autosuggest = request.getParameter("autosuggest"); 
    if (autosuggest != null) {
        try {
          // get the method the user has specified for auto-suggestion
          // the reference to the method is available in the "method"
          // parameter
          MethodExpression mx =
            ctx.getApplication().getExpressionFactory().
               createMethodExpression(ctx.getELContext(),
                                      request.getParameter("method"),
                                      String.class, PARAMS);
          // get the auto suggestion result from the method 
          Object[] args = new Object[] { autosuggest };
          Object[] result = mx.invoke(ctx.getELContext(), args);
          // send the suggestions to the client using JSON utilities
          JSONUtil.write(response.getHttpResponse().getOutputStream(), 
                         result);
        } catch (Exception e) {
          // log error
        } finally {
          // cut the lifecycle to avoid rendering components
          ctx.responseComplete();
        }
    }
  }

  public void beforePhase(PhaseEvent event) {}

  public PhaseId getPhaseId() {
    return PhaseId.RESTORE_VIEW;
  }
}

This suggested approach still needs to be improved on to properly handle the Portlet context.

The values returned by the ExternalContext are explicitly cast into Servlet objects. This approach fails in the current Portlet context. To get the parameters correctly, you can use the following code:

ctx.getExternalContext().getParameterMap().get("autosuggest")

The Portlet bridge processes Ajax requests as JSF requests, dispatches them to the different Portlets and aggregates all of their replies into a single response. The JavaScript component within the browser will not only receive the PhaseListener response as JSON data, but the full data set with all other Portlets, which is much harder to interpret.

To avoid this, the Ajax auto-suggest request management is not hosted in a PhaseListener but an external Servlet instead. Thus, the request will not be intercepted by the Portlet bridge, and the server answers will be sent as partial JSON data as expected.

Here is a sample Servlet to replace the PhaseListener in a portal context:

public class AutoSuggestServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req,          
                       HttpServletResponse resp)
    throws ServletException, java.io.IOException {
    FacesContext ctx =
 ServletFacesUtil.createFacesContext(req, resp);    
    Map params = ctx.getExternalContext().getParameterMap();
    Object autosuggest = params.get("autosuggest");
    if (autosuggest != null) {
        try {                   
          MethodExpression mx =
            ctx.getApplication().getExpressionFactory().
               createMethodExpression(ctx.getELContext(),
                                      params.get("method"),
                                      String.class, PARAMS);          
          Object[] args = new Object[] { autosuggest };
          Object[] result = mx.invoke(ctx.getELContext(), args);         
          JSONUtil.write(resp.getOutputStream(), 
                         result);
        } catch (Exception e) {
          // log error
        } finally {
          // release our temporary FacesContext
          ctx.release();
        }
    }    
  }
}

The code is close, but instead of getting the FacesContext from the JSF API, we use ServletFacesUtil.createFacesContext() to get our own instance:

  • We do not use FacesContext.getCurrentInstance() since the instance would be null, as we are not in the FacesServlet context.
  • We do not use FacesContextFactory directly because it expects Portlet objects, like PortletContext or Portletsession, instead of Servlet objects such as ServletContext or HttpSession, because of the Portlet bridge. Remember that we use a Servlet to replace a PhaseListener. We have to retrieve or build Portlet objects before calling FacesContextFactory.

Our approach based on ServletFacesUtil.createFacesContext() works when the JSF component renderer stores the context and session objects using APPLICATION_SCOPE. These objects can then be retrieved from the Servlet, and request and response objects can be built using delegation on the corresponding Servlet objects.

Another common pitfall to coding an Ajax JSF component for Portlets is having distinct JavaScript variables share the same name among different Portlets. The solution is to prefix the variables with the Portlet namespace:

  • Use UIComponent.getClientId() as variable names, since the components are embedded in a tag
  • Or apply the ExternalContext.encodeNamespace() method from the JSF API.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.