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.
- Get the struts2-json-plugin.jar and add to the lib folder
- In the struts.xml configuration file, extend the package by json-default
- Make the result type for action mapping to be json
Lets look at the example code.
1. Action Class
package javabeat.net.struts2; 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>(); list.add("Java"); list.add("C++"); list.add("Groovy"); return "success"; } }
2. Struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="struts2demo" extends="json-default"> <action name="HelloJSONDemo" class="javabeat.net.struts2.HelloJSONAction" > <result type="json"/> </action> </package> </struts>
3. Struts 2 JSON Integration Demo
If you access the application using URL http://localhost:8080/Struts2App/HelloJSONDemo, you would see the following output.