This article will show you how to use Struts2 's Struts2-json-plugin.jar plugin to return JSON data.
First, the main steps are:
1. Copy the Struts2-json-plugin.jar plugin to the project's "/web-inf/lib" folder;
2. Write the action class file;
3. Configure this action in the Struts.xml file, the action "<package.../>" must inherit "Json-default", the action of the result type is JSON, that is, type= "JSON" and does not correspond to any view resources.
Second, the sample code:
Action class file:
Packagecom.example.action;Importjava.util.ArrayList;ImportCom.opensymphony.xwork2.ActionSupport; Public classStrutsjsonactionextendsActionsupport {Private intI=123; PrivateString str= "str"; Private int[] array={1,2,3}; PrivateArraylist<string>list; Public intGeti () {returni; } Public voidSetI (inti) { This. i =i; } PublicString getstr () {returnstr; } Public voidsetstr (String str) { This. str =str; } Public int[] GetArray () {returnArray; } Public voidSetArray (int[] Array) { This. Array =Array; } PublicArraylist<string>getList () {returnlist; } Public voidSetlist (arraylist<string>list) { This. List =list; } PublicString Execute () {list=NewArraylist<string>(); List.add ("Red"); List.add ("Green"); List.add ("Yellow"); returnSUCCESS; }}
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> < Packagename= "Json-example"namespace="/"extends= "Json-default"> <Actionname= "Jsonexample"class= "Com.example.action.StrutsJsonAction"> <resultname= "Success"type= "JSON"/> </Action> </ Package></Struts>
Then access "http://localhost:8080/Struts2_JSON/JSONExample" in the browser to display the results
The JSON plug-in serializes all serializable action properties into JSON data.
Third, configure the JSON type of result:
Serialization contains the attributes:
<resulttype= "JSON"> <!--whether to cancel the browser cache - <paramname= "NoCache">True</param> <!--Setting the server response type - <paramname= "ContentType">Application/json</param> <!--matching expression property names are serialized - <paramname= "Includeproperties">I,str</param> </result>
Serializes only the specified action property:
<resulttype= "JSON"> <!--whether to cancel the browser cache - <paramname= "NoCache">True</param> <!--Setting the server response type - <paramname= "ContentType">Application/json</param> <!--serializes only the properties specified within the action - <paramname= "root">List</param></result>
STRUTS2 return JSON data (using STRUTS2 plugin)