Suggested Pages

Monday, October 1, 2012

Servlet providing JSON Response

In this post we'll see a simple Servlet that provides an HTTP response in JSON format. To print the response in a JSON format, I'm going to use a library called Jackson.

STEP-1: Adding maven dependencies into your pom.xml


pom.xml
<repositories>
    <repository>
 <id>codehaus-snapshots</id>
 <url>http://snapshots.repository.codehaus.org</url>
    </repository>
</repositories>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
   


STEP-2: Create the Servlet


JsonServler.java

package com.simonefolinoblogspot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

public class JsonServlet extends HttpServlet{

 private static final long serialVersionUID = 7905177450045184525L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  System.out.println("JsonServlet--start");
  System.out.println("requestURI="+req.getRequestURI());
  Items items=new Items();
  List listItems = new LinkedList();
  Item item=new Item();
  item.setValue("val1");
  Item item2=new Item();
  item2.setValue("val2");
  listItems.add(item);
  listItems.add(item2);
  items.setItems(listItems);
  resp.setContentType("application/json");
  PrintWriter out = resp.getWriter();
  ObjectMapper mapper = new ObjectMapper(); 
  mapper.writeValue(out, items);
  System.out.println("JsonServlet--end");
 }
 
}


As you can see I made use of ObjectMapper object that permits to print an application domain object in JSON format.
Items.java

package com.simonefolinoblogspot.servlet;

import java.util.List;

public class Items {
 
 private List<Item> items;

 public List<Item> getItems() {
  return items;
 }

 public void setItems(List<Item> items) {
  this.items = items;
 }

 @Override
 public String toString() {
  return "Items [items=" + items + "]";
 }
 
}

Item.java

package com.simonefolinoblogspot.servlet;

public class Item {

 private String value;

 public String getValue() {
  return value;
 }

 public void setValue(String value) {
  this.value = value;
 }

 @Override
 public String toString() {
  return "Item [value=" + value + "]";
 }
}

When the Servlet is invoked the response is in JSON format and is something like this:
Response

{"items":[{"value":"val1"},{"value":"val2"}]}


No comments :

Post a Comment

Suggested Pages