We will:
- Create a Java object
- Convert it to a JSON string
- Transfer the JSON string to Javascript
- Unmarshal the JSON string to a javascript object
- Display the javascript object
First we will need a JSON library to help us stringify our Java object.
Update your ivy.xml to get the jason.jar, like this:
<ivy-module version="2.0">
<info organisation="org.confucius" module="helloworld"/>
<dependencies>
<dependency org="org.json" name="json" rev="20090211"/>
<dependency org="javax.servlet" name="servlet-api" rev="2.5"/>
<dependency org="javax.servlet" name="jsp-api" rev="2.0"/>
<dependency org="jstl" name="jstl" rev="1.2"/>
<dependency org="log4j" name="log4j" rev="1.2.16"/>
</dependencies>
</ivy-module>
Now execute the 'resolve' target in your Ant build.xml to download the json.jar to your /lib folder.
In Eclipse, go to Project->Properties->Java Build Path->Libraries->Add Jars
Add the json.jar so Eclipse includes it in its CLASSPATH.
Also, update your Ant build.xml to include the json.jar in its CLASSPATH. Like this:
<project name="HelloWorld" xmlns:ivy="antlib:org.apache.ivy.ant" >
<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve />
</target>
<target name="init" depends="resolve">
<mkdir dir="classes"/>
<mkdir dir="target"/>
</target>
<target name="compile" depends="init">
<javac srcdir="." destdir="classes">
<classpath>
<pathelement location="lib/json-20090211.jar"/>
<pathelement location="lib/servlet-api-2.5.jar"/>
<pathelement location="lib/jsp-api-2.0.jar"/>
<pathelement location="lib/log4j-1.2.16.jar"/>
</classpath>
</javac>
</target>
<target name="dist" depends="compile">
<war destfile="target/HelloWorld.war" webxml="web.xml">
<classes dir="classes"/>
<lib dir="lib">
<exclude name="jsp-api*.jar"/>
</lib>
<fileset dir="web-content"/>
<webinf dir="WEB-INF"/>
</war>
<echo>Build executed at ${TIME_NOW}</echo>
</target>
<tstamp>
<format property="TIME_NOW" pattern="hh:mm:ss aa MM/dd/yyyy"/>
</tstamp>
</project>
Now let us create a Java class in org.confucius called MusicSchool.java.
It looks like this:
package org.confucius;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MusicSchool {
private String name;
private String address;
private List<String> instruments;
public MusicSchool(){
name = new String("Beethoven Music School");
address = new String("9000 Cliff Drive, Santa Cruz, California");
instruments = new ArrayList<String>();
instruments.add("Piano");
instruments.add("Guitar");
instruments.add("Trumpet");
instruments.add("Violin");
}
public String getJSON() {
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("name", name);
jsonObj.put("address", address);
jsonObj.put("instruments", new JSONArray(instruments));
return jsonObj.toString();
} catch (JSONException e) {
return (e.toString());
}
}
}
It contains two string fields, 'name' and 'address' which holds the name and address of the music school.
It also has a field 'instruments' which is a list of the different instruments taught at the school.
It has a constructor which creates a default school (Beethoven Music School).
And, most importantly, it has a method getJSON() which converts the object to a JSON string.
We will now update HelloWorld.java servlet to return this MusicSchool object.
It looks like this:
package org.confucius;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MusicSchool musicSchool = new MusicSchool();
response.getWriter().println(musicSchool.getJSON());
}
}
Next, we will update HelloWorld.jsp to make an AJAX call and get this MusicSchool object as a JSON string.
It looks like this:
Most of this code is standard AJAX code which we saw in the earlier AJAX post.
<html>
<head>
<script src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function getMusicSchool()
{
// Create AJAX object
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
// Associate a method for AJAX response
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Successful response
getJSONObject(xmlhttp.responseText);
}
// Send AJAX request
xmlhttp.open("GET","http://localhost:8080/HelloWorld/music-school",true);
xmlhttp.send();
}
function getJSONObject(jsonStr)
{
if (null != jsonStr && 0 != jsonStr.length)
{
alert(jsonStr)
try
{
jsonObj = $.parseJSON( jsonStr );
displatStr = jsonObj.name + ", located at " + jsonObj.address + " teaches " + jsonObj.instruments.length + " instruments, including " + jsonObj.instruments[1] + ".";
alert(displatStr);
}
catch(e)
{
alert(e.toString());
}
}
}
</script>
</head>
<body>
<form>
<button type="button" onclick="getMusicSchool()">Show Music School</button>
</form>
</body>
</html>
The new function is getJSONObject().
This function uses the JQuery JSON library to unmarshal the JSON string into a javascript object. It then displays first the raw JSON string, and then the javascript object.
Update your web.xml to direct /music-school URLs to HelloWorld.java servlet.
Like this:
<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/music-school</url-pattern>
</servlet-mapping>
</web-app>
If you build and deploy HelloWorld.war, and browse to:
http://localhost:8080/HelloWorld/jsp/HelloWorld.jsp
you will be able to see both the JSON string and the Javascript presentation.
JSON has provided us with a standardized format for transferring Java objects.
No comments:
Post a Comment