Ajax in JSF 1.2

This is the first time, i use JSF framework. Need time to understand this framework’s flow 😀
Then, i got job for making AJAX in JSF, wuuw~ When i google it, i found many tutorials, but most of them using JSF 2.0.
I need AJAX for JSF 1.2 because i’m using JSF 1.2 in current development.
In JSF 2.0. you can easily use AJAX because this is one of the new features in ver 2.0.
In the other hand, you need more effort to do AJAX in JSF 1.2. 😉
After searching it for a while, i found a tutorial for creating AJAX using PhaseListener in JSF 1.2.
So, i wanna share this code 😀
I use this in Websphere, Oracle for database, and JSON for response data format.

Okay, Let’s see the step by step,

  1. Creating a new Class AjaxPhaseListener. Before creating the new class, create package. In my case, i create package “com.testing.ajax” then place the AjaxPhaseListener class inside. I use json-simple library for formatting the response data.
    package com.testing.ajax;
    
    /*
     * by Ananti
     */
    
    import java.io.IOException;
    import java.io.StringWriter;
    import java.util.List;
    import javax.faces.context.FacesContext;
    import javax.faces.event.PhaseEvent;
    import javax.faces.event.PhaseId;
    import javax.faces.event.PhaseListener;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.json.simple.JSONArray;
    
    public class AjaxPhaseListener implements PhaseListener{
    	public void afterPhase(PhaseEvent event) {
    		// TODO Auto-generated method stub
    		String viewId = event.getFacesContext().getViewRoot().getViewId();
    		if (viewId.indexOf("Ajax") != -1) {
    			 handleAjaxRequest(event);
    		}
    	}
    
    	private void handleAjaxRequest(PhaseEvent event) {
    		FacesContext context = event.getFacesContext();
    		HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    		Object object = context.getExternalContext().getRequest();
    		if (!(object instanceof HttpServletRequest)) {
    			return;
    		}
    
    		HttpServletRequest request = (HttpServletRequest)object;
    		JSONArray arr = new JSONArray();
    		arr.add("Response1");
    		arr.add("Response2");
    		arr.add("Response3");
    
    		//preparation for response using json array
    		StringWriter out = new StringWriter();
    		try {
    			arr.writeJSONString(out);
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		String jsonText = out.toString();
    
    		try {
    			response.setHeader("Cache-control", "no-cache");
    			response.getWriter().write(jsonText);
    			event.getFacesContext().responseComplete();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	public void beforePhase(PhaseEvent arg0) {
    		// TODO Auto-generated method stub
    
    	}
    
    	public PhaseId getPhaseId() {
    		// TODO Auto-generated method stub
    		return PhaseId.RESTORE_VIEW;
    	}
    
    }
    
    
  2. Add <lifecycle> element into faces-config.xml, after changing the faces-config.xml, you should restart your web server (in my case, restart the websphere).
    
    		com.testing.ajax.AjaxPhaseListener
    
  3. Call Ajax from .jsp file (.faces)
    
    	Ajax JSF 1.2
    
    <script type="text/javascript">
             function getAjax() {
    		var url = "Ajax.faces";
    		if (window.XMLHttpRequest) {
    			//native support for XMLHttpRequest object
    			req = new XMLHttpRequest();
    		} else if (window.ActiveXObject) {
    			//for IE browser
    			req = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		req.onreadystatechange = function() {
    			if (req.readyState==4 && req.status==200) {
    				var jsonParse = JSON.parse(req.responseText,',');
    				document.getElementById('result').value = jsonParse[0] + '&' + jsonParse[1] + '&' + jsonParse[2];
    			}
    		}
    		req.open("GET",url,true);
    		req.send();
    	}
    
    </script>
    
     <input onclick="getAjax()" type="button" value="get AJAX" />
     <input id="result" type="text" />
    
    

Simple, isn’t it? 😀
GoodLuck! 😉

Ajax in JSF 1.2

3 thoughts on “Ajax in JSF 1.2

  1. abc says:

    the background is too distracting .. it would be easier for people to read your blog if you make the background less distracting … BTW good article

  2. Mina says:

    what about submitting a form with values obtained via ajax call….it is returned with null
    since ajax returned value have a scope less than request scope so it do not get sent when submitting form

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s