Struts 2 And JSON Example

In this tutorial we will see that how to display result as JSON format instead of HTML view, JSON(Java Script Object Notation) is light weighted object very use full in mobile technology. It took a decent amount of time to figure out how to set up struts 2 with JSON.

There are a few things that need to be done in order to use JSON with struts 2. Basically, struts provides you with a few result types. For JSON, you will require a new Result Type, because, obviously, since the response is a JSON response, you dont have a page to redirect to.

So, first you need to download the JSON plugin, if you already dont have it in your struts download. As usual, keep it in the lib folder of your application.

The struts 2 JSON plugin allows you to create an action that can be serialized into a JSON object. Ok, what that means in basic terms is that in the response that is sent back to the client, the response is the Javascript object that represents the Action class, and the attributes of the javascipt object are actually named after the public getter methods of the action. If the value of any getter method returns a null, the value of the javascript attribute will be null and vice versa.

The plugin not only handles basic types but also complex types like lists and arrays. We will see a code snippet shortly.
First things first. Lets see what needs to be done for setting up our action for JSON.

Keep the json plugin jar in your lib directory.In struts.xml, create a new package that extends json-default. If you want to use an existing package, you can simply use a comma separated value for the package names as the value of the extends parameter of the package tag. That is what I will be doing here. (TIP : json-default package extends struts-default.)Specify the result type of your action class to be ‘json’

That is pretty much all you need to do to get things going from the struts configuration perspective.
The json-default package contains an interceptor and the result type configuration for JSON requests and responses.
Now lets get to the code.

Create Action Class
JSONAction.java

package com.dineshonjava.struts2.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;

/**
 * @author Dinesh Rajput
 *
 */
public class JSONAction{

 private static final long serialVersionUID = 1L;
 
 private String name = "Dinesh";
 private String[] cityArray = {"Noida","Delhi", "Mumbai"};
 private int age = 27;
 private int[] pincodeArray = {20301,110006,210081};
 private List<String> lists = new ArrayList<String>();
 private Map<String, String> maps = new HashMap<String, String>();
 
 //no getter method, will not include in the JSON
 private String otherName = "Other";
 
 public JSONAction(){
  lists.add("list1");
  lists.add("list2");
  lists.add("list3");
  lists.add("list4");
  lists.add("list5");
 
  maps.put("key1", "value1");
  maps.put("key2", "value2");
  maps.put("key3", "value3");
  maps.put("key4", "value4");
  maps.put("key5", "value5");
 }
 
 public String execute() {
  return Action.SUCCESS;
    }
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String[] getCityArray() {
  return cityArray;
 }

 public void setCityArray(String[] cityArray) {
  this.cityArray = cityArray;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public int[] getPincodeArray() {
  return pincodeArray;
 }

 public void setPincodeArray(int[] pincodeArray) {
  this.pincodeArray = pincodeArray;
 }

 public List<String> getLists() {
  return lists;
 }
 
 public void setLists(List<String> lists) {
  this.lists = lists;
 }
 
 public Map<String, String> getMaps() {
  return maps;
 }
 
 public void setMaps(Map<String, String> maps) {
  this.maps = maps;
 }
 
}

Create Configuration file:
struts.xml

To output the JSON data, you need to declared a package which extends the “json-default“, and result type as “json“.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.devMode" value="true" />
  
  <package name="default" extends="json-default" namespace="/">
        <action name="getjson" class="com.dineshonjava.struts2.action.JSONAction">
            <result type="json"/>
        </action>
    </package>
   
</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2JsonIntegration</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>json.action</welcome-file>
    </welcome-file-list>
</web-app>

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/getjson.

This will give you following screen:

 

Struts 2 And JSON Example

Download Source Code + Libs
Struts2JSONIntegration.zip

<<Previous <<   || Index ||   >>Next >>
Previous
Next