If it is an HTTP+JSON interface project as a client and there are no JSP and other view views, using the Jersery framework is definitely the first choice. Under the Spring3 MVC-based architecture, the return type of HTTP+JSON is also very supportive. However, in development work, it is very common for the upgrade of functions to be based on the established architecture. I encountered the need to use the HTTP+JSON return type interface based on Struts2, which is based on the established framework structure.
There are two ways to return JSON in Struts2: 1. Use the output stream of Servlet to write JSON string; 2. Use Struts2 to extend JSON.
1. Use Servlet output stream
The essence of the JSON interface is: During the process of passing JSON data, it is actually just passing an ordinary string that conforms to the JSON syntax format. The so-called "JSON object" refers to the result of parsing and wrapping this JSON string.
So here you only need to write a string in JSON syntax format to the Servlet's HttpServletResponse. Here you use the PrintWriter method, and of course you can also use the Stream stream method. It should be noted that the encoding is not set before calling getWriter (either called setContentType or setCharacterEncoding method to set encoding), HttpServletResponse will return a PrintWriter instance encoded with the default encoding (either ISO-8859-1). This will cause garbled Chinese. Moreover, when setting encoding, it must be set before calling getWriter, otherwise it will be invalid.
Write interface code:
The difference between the method here and the general Struts2 method is that this is the void return type.
public void write() throws IOException{ HttpServletResponse response=ServletActionContext.getResponse(); /* * Encoding is not set before calling getWriter (either called setContentType or setCharacterEncoding method to set), * HttpServletResponse will return a PrintWriter instance encoded with the default encoding (either ISO-8859-1). This will cause garbled Chinese. Moreover, when setting encoding, it must be set before calling getWriter, otherwise it will be invalid. * */ response.setContentType("text/html;charset=utf-8"); //response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //JSON is passed in the form of a normal string during the delivery process. Here is a simple splicing of one for testing String jsonString="{/"user/":{/"id/":/"123/",/"name/":/"Zhang San/",/"say/":/"Hello , i am a action to print a json!/",/"password/":/"JSON/"},/"success/":true}"; out.println(jsonString); out.flush(); out.close(); }Configuration action
From the following configuration, it can be clearly seen that the configuration is no different from the normal action configuration, but there is no return view.
<action name="write" method="write" />
Return value
{"user":{"id":"123","name":"Zhang San","say":"Hello , i am a action to print a json!","password":"JSON"},"success":true}2. Extension of JSON using Struts2
To use this extension, you will definitely need to add a support package. After my debugging, here are two options:
1.xwork-core-2.1.6.jar and struts2-json-plugin-2.1.8.jar. If you want to use struts2-json-plugin-2.1.8.jar, your xwork-core-*.jar cannot choose 2.2.1 and above versions, because the 2.2.1 and above versions of xwork-core-*.jar do not have packages such as org.apache.commons.lang. When starting tomcat, it will appear: java.lang.NoClassDefFoundError: org.apache.commons.lang.xwork.StringUtils.
2.xwork-2.1.2.jar and jsonplugin-0.34.jar. If you want to use jsonplugin-0.34.jar to support, you need to switch your xwork-core-*.jar to xwork-2.1.2.jar. Because jsonplugin-0.34.jar requires support for com.opensymphony.xwork2.util.TextUtils. The 2.2.1 and above versions of xwork-core-*.jar are found, and there is no such class in xwork-core-2.1.6.jar.
Finally, I want to say that it is really not worth it because of the original construction method. I am really tired. Using automated components such as Maven will largely avoid bugs that rely on version differences between the private parts. The component method of maven will be used in the "struts2 zero configuration" in the third section.
Writing interface code
In this class, the json() method is the ordinary Struts2 method. I don't see any strings in JSON format here, because we're going to leave this work to the extension to do it. Without any settings, the return values of all getter methods under the class will be included in the JSON string returned to the client. To eliminate attributes that do not need to be included, you need to use @JSON(serialize=false) on the getter method for annotation in the class structure. Of course, you can also directly remove this getter method when it does not affect other businesses. So the return result in this example is a JSON-format string that converts the dataMap object to.
package json; import java.util.HashMap; import java.util.Map; import org.apache.struts2.json.annotations.JSON; import com.opensymphony.xwork2.ActionSupport; /** * JSON test* * @author Watson Xu * @date 2012-8-4 06:21:01 pm */ public class JsonAction extends ActionSupport{ private static final long serialVersionUID = 1L; private Map<String,Object> dataMap; private String key = "Just see see"; public String json() { // The data in the dataMap will be converted to a JSON string by Struts2, so you must first clear the data in it. dataMap = new HashMap<String, Object>(); User user = new User(); user.setName("Zhang San"); user.setPassword("123"); dataMap.put("user", user); // Put in a tag whether the operation is successful dataMap.put("success", true); // Return the result return SUCCESS; } public Map<String, Object> getDataMap() { return dataMap; } //Set the key attribute not to return as json's content @JSON(serialize=false) public String getKey() { return key; } }Configure aciton
In the configuration, first, the package where the action is located needs to inherit json-default, or the inherited parent package inherits json-default. This configures the return type of action to json, and can configure its serialized properties and other class parameters.
<?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> <package name="json" extends="struts-default,json-default" > <action name="json" method="json"> <result type="json"> <!-- Here we specify the attribute to be serialized by Struts2. This attribute must have a corresponding getter method in the action --> <param name="root">dataMap</param> </result> </action> </package> </struts>
Return value
{"success":true,"user":{"name":"Zhang San","password":"123"}}3. How to use Struts2 zero configuration, using Maven component:
3.1) To build a webapp, we still use Maven to build it. The construction process refers to limingnihao's blog: Use Eclipse to build Maven's SpringMVC project.
3.2) Add Struts2 dependency, struts2 zero configuration dependency and struts2 json dependency:
<dependencies> <!-- struts2 core dependency--> <dependency> <groupId>org.apache.structs</groupId> <artifactId>structs2-core</artifactId> <version>2.3.4</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- struts2 zero configuration dependency--> <dependency> <groupId>org.apache.structs</groupId> <artifactId>structs2-convention-plugin</artifactId> <version>2.3.4</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- struts2's json dependency--> <dependency> <groupId>org.apache.structs</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.4</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>
After testing, there is no version-compatible bug in the above dependency room, not only because they are the same version, but also because of Maven's automatic construction method.
3.3) Configure web.xml and enable Struts2:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>StrutsPrepareAndExecuteFilter </filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> <init-param> <param-name>config</param-name> <param-value>struts-default.xml,struts-plugin.xml,struts.xml</param-value> </init-param> </filter> <filter-mapping> <filter-name>StrutsPrepareAndExecuteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3.4) Configure struts.xml and set some basic constants and applications:
<?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> <package name="base" extends="json-default,struts-default"> <!-- Here you can set some global return value mapping relationships, etc. --> </package> <constant name="struts.action.extension" value="" /> <constant name="struts.ui.theme" value="simple" /> <constant name="struts.i18n.encoding" value="utf-8" /> <constant name="struts.multipart.maxSize" value="1073741824"/> <constant name="struts.devMode" value="false"/> </struts>
3.5) Write and configure Action. Set by no Convention specified, so for the Convention plugin, it will treat all java classes with class names ending with Action as Action:
package watson.action; import java.util.HashMap; import java.util.Map; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; @ParentPackage("base") @Namespace("/watson") @Results({ @Result(name = "json",type="json", params={"root","msg"}) }) public class JsonAction { @Action(value="json") public String json() { msg = new HashMap<String, Object>(); msg.put("flag", "success"); Map<String, String> user = new HashMap<String, String>(); user.put("name", "Zhang San"); user.put("age", "34"); msg.put("user", user); return "json"; } //======================================= private Map<String, Object> msg; public Map<String, Object> getMsg() { return msg; } } 3.6) Deploy the project, start the container, and enter: http://localhost:7070/Struts2foo/watson/json in the browser address bar. Wait until the results are as follows:
{"flag":"success","user":{"age":"34","name":"Zhang San"}}From the above results, we can see that after zero configuration is enabled, the configuration in xml is missing, and instead annotated with annotation in each action. Here we delete the above configuration in xml and write the following code to the upper part of the above JsonAction:
@ParentPackage("base") @Namespace("/watson") @Results({ @Result(name = "json",type="json", params={"root","msg"}) })root is equivalent to the parameter configuration in the XML configuration.
4. Attachment:
Detailed explanation of configurable parameters when the return type of action is json:
<result type="json"> <!-- Here specifies the properties that will be serialized by Struts2. This property must have a corresponding getter method in the action --> <!-- By default, the values of all getter methods with return values will be sequenced, regardless of whether the method has corresponding properties --> <param name="root">dataMap</param> <!-- Specifies whether to serialize empty properties --> <param name="excludeNullProperties">true</param> <!-- Specifies the properties in the serialized dataMap --> <param name="includeProperties">userList.*</param> <!-- Here specifies which properties will be excluded from the dataMap. These excluded properties will not be serialized, and generally do not appear at the same time as the above parameter configuration --> <param name="excludeProperties">SUCCESS</param> </result>
Attachment download
StrutsJson.rar
Struts2foo.rar
The above is the entire content of Struts2 returning JSON objects. I hope it can give you a reference and I hope you can support Wulin.com more.