FileDocCategorySizeDatePackage
ZipCodePhaseListener.javaAPI DocExample2019Tue Sep 05 08:48:10 BST 2006com.oreilly.ajax

ZipCodePhaseListener

public class ZipCodePhaseListener extends Object implements javax.faces.event.PhaseListener

Fields Summary
Constructors Summary
Methods Summary
public voidafterPhase(javax.faces.event.PhaseEvent event)

    String viewId = event.getFacesContext().getViewRoot().getViewId();
    if (viewId.indexOf("Ajax") != -1)
    {
      handleAjaxRequest(event);
    }
  
public voidbeforePhase(javax.faces.event.PhaseEvent arg0)

    //not used, but implemented to satisfy compiler
  
public javax.faces.event.PhaseIdgetPhaseId()

    return PhaseId.RESTORE_VIEW;
  
private voidhandleAjaxRequest(javax.faces.event.PhaseEvent event)

    FacesContext context = event.getFacesContext();
    HttpServletResponse response = (HttpServletResponse) context
        .getExternalContext().getResponse();
    Object object = context.getExternalContext().getRequest();
    if (!(object instanceof HttpServletRequest))
    {
      //Only handle HttpServletRequests 
      return;
    }

    HttpServletRequest request = (HttpServletRequest) object;
    String zipcode = request.getParameter("zip");
    Location location = ZipcodeManager.getZipcode(zipcode);

    // actually render using XML.
    StringBuffer returnXML = null;
    returnXML = new StringBuffer("\r\n<location>");
    returnXML.append("\r\n<city>"+
                        location.getCity()+"</city>");
    returnXML.append("\r\n<state>"+
                        location.getState()+"</state>");
    returnXML.append("\r\n</location>");
    
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    try
    {
      response.getWriter().write(returnXML.toString());
      event.getFacesContext().responseComplete();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }