Tuesday 1 January 2013

Struts and JSON

What is Struts?

Struts is a popular open source framework from Apache Software Foundation based on MVC (model-view-controller) architecture. Though there are many other MVC frameworks available like Spring MVC, JSF in the market to develop web applications, Struts has retained its popularity because of its simple architecture and low learning curve. 

What is JSON?

JSON stands for Java Script Object Notation. It is a light weight data-interchange format using which we can easily parse and generate data. It is language independent, yet it uses popular object oriented convention.  Slowly and slowly it is getting accepted by the software industry as a formidable challenger to XML, the other popular format.


Converting an Object to JSON format using Struts

Now let us come to first thing first i.e., how to convert a Java object to JSON format using Struts. I have described the steps of accomplishing this below.

Softwares / Tools

1. Struts 2.3.7
2. JDK 7
3. Eclipse Indigo Service Release 2
4. Apache Tomcat v7.0

Steps

  • Create a Web Application project in eclipse by selecting 'Dynamic Web Project' under 'Web' in 'New Project' wizard. Name the project as 'StrutsApp'.
  •  Place all jars from Struts 2.3.7 archive into WEB-INF/lib folder of our application. Make sure following jars are present: struts-core-1.3.10.jar, struts2-core-2.3.7.jar, struts2-json-plugin-2.3.7.jar. Remove other jars which you don't need because Struts 2.3.7 comes with other plugin jars like spring, junit etc.
  • In web.xml file, declare StrutsPrepareAndExecuteFilter as follows.
<?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>StrutsApp</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  • Let us create the Java class for the entity which we want to convert into JSON format.
package com.programnplay.entity;

public class Item {
   
    private String id;
    private String mfgDate;
    private String expDate;
    private String color;
    private String description;
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMfgDate() {
        return mfgDate;
    }
    public void setMfgDate(String mfgDate) {
        this.mfgDate = mfgDate;
    }
    public String getExpDate() {
        return expDate;
    }
    public void setExpDate(String expDate) {
        this.expDate = expDate;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
   
   
}
 
Above class 'Item' is a simple POJO class with different attributes and setter and getter methods.
  • Next we have to create an action class which will retrieve a list of Item objects from the back-end and send this list to presentation layer.
package com.programnplay.action;
import java.util.ArrayList;
import java.util.List;

import com.programnplay.entity.Item;

public class ItemAction {
   
    private List data = new ArrayList();
   
    public String execute() {
        Item item1 = new Item();
        item1.setColor("blue");
        item1.setDescription("Item 1");
        item1.setId("123");
        item1.setMfgDate("December 21, 2012");
        item1.setExpDate("December 21, 2012");
       
        Item item2 = new Item();
        item2.setColor("green");
        item2.setDescription("Item 2");
        item2.setId("456");
        item2.setMfgDate("December 20, 2012");
        item2.setExpDate("December 20, 2012");
       
        data.add(item1);
        data.add(item2);
        setData(data);
        return "SUCCESS";
    }

    public List
getData() {
        return data;
    }

    public void setData(List
data) {
        this.data = data;
    }
}
This is a simple Action class with execute() method. There is an attribute 'data' that holds a set of 'Item' objects.
  • Here comes the important step. Though through the above action class, we will get a list of 'Item' objects, it will not be in JSON fomat. To do so, we have to modify struts.xml file as follows.
<?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>
    <package name="default" extends="struts-default, json-default">
        <action name="" class="com.
programnplay.action.ItemAction">
            <result name="SUCCESS" type="json"></result>
        </action>
    </package>
</struts>

  • We are done with coding now. So start Tomcat Server, open the browser and place the url http://localhost:8080/StrutsApp in address bar. We will get a screen similar as follows:

Running the App
Note: While Firefox fully supports JSON format, some browsers like IE or internal browser of Eclipse may ask you to open/save the file instead of displaying the data inside browser. But the content will remain same.

Hurray! See you in my next techno blog.

No comments:

Post a Comment