Struts2 returns Json data (using the Struts2 plug-in), jsonstruts2
This article describes how to use the Struts2 struts2-json-plugin.jar plug-in to return JSON data.
1. The main steps are as follows:
1. Copy the struts2-json-plugin.jar plug-in to the project's "/WEB-INF/lib" folder;
2. Compile an Action file;
3. in struts. configure the Action in the xml file. The "<package... /> "must inherit" json-default ". The Result type of the Action is json, that is, type =" json ", and does not correspond to any view resource.
Ii. Sample Code:
Action files:
package com.example.action;import java.util.ArrayList;import com.opensymphony.xwork2.ActionSupport;public class StrutsJsonAction extends ActionSupport { private int i=123; private String str="str"; private int[] array={1,2,3}; private ArrayList<String> list; public int getI() { return i; } public void setI(int i) { this.i = i; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public int[] getArray() { return array; } public void setArray(int[] array) { this.array = array; } public ArrayList<String> getList() { return list; } public void setList(ArrayList<String> list) { this.list = list; } public String execute(){ list = new ArrayList<String>(); list.add("red"); list.add("green"); list.add("yellow"); return SUCCESS; }}
Struts. xml file:
<?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> <package name="json-example" namespace="/" extends="json-default"> <action name="JSONExample" class="com.example.action.StrutsJsonAction"> <result name="success" type="json"/> </action> </package></struts>
Access "http: // localhost: 8080/Struts2_JSON/JSONExample" in the browser, and the result is displayed.
The JSON plugin serializes all serializable Action attributes into JSON data.
3. Configure the Result of the JSON type:
Serialization includes the following attributes:
<Result type = "json"> <! -- Disable browser cache --> <param name = "noCache"> true </param> <! -- Set the server response type --> <param name = "contentType"> application/json </param> <! -- All matching expression attribute names will be serialized --> <param name = "includeProperties"> I, str </param> </result>
Serialize only the specified Action attribute:
<Result type = "json"> <! -- Disable browser cache --> <param name = "noCache"> true </param> <! -- Set the server response type --> <param name = "contentType"> application/json </param> <! -- Only serialize the specified attribute in the Action --> <param name = "root"> list </param> </result>