Struts2

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:

 

Download Source Code + Libs
Struts2JSONIntegration.zip

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago