JSON and Servlet example
In the previous section of JSON-Java example youhave learned how to create a java class by using JSON classes. Now inthis example we will tell you how to use JSON classes for creating Servlet.
In this example we have created an object of JSONArrayand then we have added elements into this array by using the method add().To have functionality of JSON in your application you must have JSON-lib andits supported jar files. These are: commons-lang.jar,commons-beanutils.jar, commons-collections.jar,commons-logging.jar, ezmorph.jarand json-lib-2.2.2-jdk15.jar.
Here is the example code of JSONServlet.java asfollows:
JSONServlet.java
import java.io.*; |
We have to do corresponding servlet mapping into web.xmlas given below:
<?xml version="1.0" encoding="ISO-8859-1"?> |
To run this example follow this step by step procedure:
- create a JSONServlet.java class
- compile JSONServlet and place it into WEB-INF/classes directory
- Download JSONLibraries and place it into Tomcat's lib directory
- Start Tomcat Webserver and type
http://localhost:8080/JSON/JSONServlet into browser's address bar you will have following output on your browser.
Output:
Download JSON-Servlet Project code