Struts 2 + JSON Integration

Struts 2 provides struts2-json-plugin.jar for supporting the conversion of result type to JSON strings. Nowadays every framework supports the JSON formats because it is the most preferred format for the REST web services. This example shows how you can integrate Struts 2 and JSON.

  1. Get the struts2-json-plugin.jar and add to the lib folder
  2. In the struts.xml configuration file, extend the package by json-default
  3. Make the result type for action mapping to be json

Lets look at the example code.

1. Action Class


import java.util.ArrayList;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;

public class HelloJSONAction{
	private ArrayList<String> list;
	public ArrayList<String> getList() {
		return list;
	public void setList(ArrayList<String> list) {
		this.list = list;
	public String execute(){
		list = new ArrayList<String>();
		return "success";

2. Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "">
<constant name="struts.devMode" value="true" />
<package name="struts2demo" extends="json-default">
	<action name="HelloJSONDemo" class="" >
		<result type="json"/>

3. Struts 2 JSON Integration Demo

If you access the application using URL http://localhost:8080/Struts2App/HelloJSONDemo, you would see the following output.

Struts 2 JSON Example



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.