Using JSON with JSF

This post will describe what to do if you want to use JSON in your web applications together with JSF. JSON (JavaScript Object Notation) is a way of doing information interchange between your programming language and javascript. In other words you can use it to access for example java objects in the world of javascript, and this will give you the possibility of creating more advanced web applications. Some basic knowledge of javascript is recommended.

  1. First thing to do is to download the JSON RPC library from JsonRpc and put it in your WEB-INF/lib directory (or the directory you use that holds the libs and is packaged together with the war-file). Also remember to add the library to the classpath of your project in Eclipse or other software frameworks you use to develop.
  2. Then secondly you need to include the jsonrpc.js javascript in the header of your page. The script can be found within the downloaded lib inside \json-rpc-java-1.0.1\webapps\jsonrpc. You include it by writing something similar like this in your header:
    <script type="text/javascript" src="${pageContext.request.contextPath}/javascript/jsonrpc.js"></script>
  3. Then you need to add the servlet configuration to the web.xml
  4. Then, on top of your page (outside the <f:view> tags) you write:
    <jsp:useBean id="JSONRPCBridge" scope="session"class="com.metaparadigm.jsonrpc.JSONRPCBridge" />
  5. Then you must register the handler/backing bean you want the json to access. Do this inside the <f:view> tags but within jsp code tags
    MyHandler myHandler = (MyHandler )FacesContext.getCurrentInstance().getApplication ()
    .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(),"myHandler ");
    JSONRPCBridge.registerObject("myHandler ", myHandler );%>
  6. From javascript side, you can now access you handler, set properties and execute methods like this:
    function JsonTest()
    		//The input-parameter to the JSONRpcClient is basically the path to
    		//the servlet you registered in web.xml
    		// Call a Java method
    		var result = jsonrpc.myHandler.getTestValue();
    		//Do something with result.....
    		jsonrpc.myHandler.setTestData("SET A PROPERTY TO SOMETHING");
    		jsonrpc.myHandler.execute(); //Execute a method

Good luck!