Go Struts2 method Summary for returning JSON objects

Source: Internet
Author: User

Transferred from: http://kingxss.iteye.com/blog/1622455

If the Http+json interface works as a client, without a view view such as JSP, the use of Jersery framework development is definitely the first choice. In the SPRING3 MVC-based architecture, the return type of Http+json is also well supported. However, in the development work, the upgrade of the function is based on the established architecture is very common situation. I encountered the need to develop a Struts2-based Http+json return type interface is based on the established framework structure.

Struts2 There are two ways to return JSON: 1. Write the JSON string using the output stream of the servlet, 2. Use STRUTS2 to extend the JSON.

I. Output stream using the servlet

The essence of JSON interface is:JSON data in the process, in fact, is to pass a common JSON syntax format of the string, so-called "JSON object" refers to this JSON string parsing and packaging results.

So here we just need to write a JSON-syntactically formatted string to the servlet's HttpServletResponse, which uses the PrintWriter way, and of course the stream stream. It is important to note that the encoding is not set before calling Getwriter (either by calling setContentType or Setcharacterencoding method setting encoding), and HttpServletResponse returns a default encoding ( ISO-8859-1) encoded PrintWriter instance. This will cause Chinese garbled characters. And the encoding must be set before calling Getwriter, otherwise it is invalid.

Write the interface code:

The difference between the method here and the general Struts2 method is that this is the void return type.

 Public voidwrite () throws Ioexception{httpservletresponse response=servletactioncontext.getresponse ();/** The encoding is not set before calling Getwriter (both calling setContentType or Setcharacterencoding method setting encoding), * HttpServletResponse will return a default encoding ( ISO-8859-1) encoded PrintWriter instance. This will * cause the Chinese garbled. And the encoding must be set before calling Getwriter, otherwise it is invalid. * */Response.setcontenttype ("Text/html;charset=utf-8");//response.setcharacterencoding ("UTF-8");PrintWriter out=Response.getwriter ();//JSON is passed as a normal string in the process of passing, and here is a simple concatenation of a testString 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 ();}

Configure action

From the configuration below you can see clearly that the configuration is no different from the normal action configuration, just not the view returned.

Class

return value

{"User": {"id": "123", "Name": "Zhang San", "Say": "Hello, I am a action to print a json!", "Password": "JSON"}, "Success":True 

Two. Using STRUTS2 to extend JSON

To use this extension, you 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 this support method, your Xwork-core-*.jar cannot choose 2.2.1 and above version, because xwork-core-*. The 2.2.1 and above versions of the jar do not have org.apache.commons.lang packages. When you start Tomcat, it appears: 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 this way of support, it is necessary to switch your xwork-core-*.jar to Xwork-2.1.2.jar. Because Jsonplugin-0.34.jar needs com.opensymphony.xwork2.util.TextUtils.

Support for this class. and Xwork-core-*.jar's 2.2.1 or more versions are found for this class, and there is no such class in Xwork-core-2.1.6.jar.

Finally say a sentence, also because uses the original construction way and keep Wade Thunder, really not worth, really tired. Using automation artifacts such as Maven can largely avoid bugs that rely on version differences between packages. In section III, "STRUTS2 0 Configuration" uses Maven's artifacts.

Writing Interface Code

The JSON () method in this class is a common Struts2 method. We don't see any JSON-formatted strings here, because we're going to give this work to the extension to complete. In the absence of any settings, the return value of all getter methods under the class change is included in the JSON string returned to the client. To exclude attributes that you do not need to include, you need to annotate the Getter method with @json (Serialize=false) in the class structure, but you can also remove the getter method directly without affecting the other business. So the return result in this example is a JSON-formatted string that converts the Datamap object.

 PackageJSON;ImportJava.util.HashMap;ImportJava.util.Map;ImportOrg.apache.struts2.json.annotations.JSON;ImportCom.opensymphony.xwork2.ActionSupport;/*** JSON Test * *@authorWatson xu* @date 2012-8-4 pm 06:21:01*/ Public classJsonactionextendsactionsupport{Private Static Final LongSerialversionuid = 1L;PrivateMap<string,object>DataMap;PrivateString key = "Just See"; PublicString json () {//the data in the Datamap will be converted to a JSON string by STRUTS2, so the data in it should be emptied first.DataMap =NewHashmap<string, object>(); User User=NewUser (); User.setname ("Zhang San"); User.setpassword ("123");d Atamap.put ("User", user);//put in a sign of whether the operation was successfulDatamap.put ("Success",true);//return ResultsreturnSUCCESS;} PublicMap<string, object>Getdatamap () {returnDataMap;}//Setting the key property is not returned as JSON content@JSON (serialize=false) PublicString GetKey () {returnkey;}}

Configure Aciton

In the configuration, the package where the action is first required inherits the Json-default, or the inherited parent bundle inherits the Json-default. This configures the return type of the action with the type JSON, and can configure some class parameters such as its serialized properties and so on

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE strutspublic "-//apache software foundation//dtd struts Configuration 2.0//en" "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts> <packageextendsclass=" Json. Jsonaction "method=" JSON "><result type=" JSON "><!--here Specifies the attribute to be Struts2 serialized, which must have a corresponding getter method in action-- ><param name= "root" >datamap</param></result></action></Package ></ Struts>

return value

{"Success":true, "user": {"name": "Zhang San", "Password": "123"}}

Three. Struts2 0 configuration usage, using MAVEN artifacts:

3.1) Build a webapp, or use MAVEN to build a process that references Limingnihao's blog: Building maven's SPRINGMVC project with Eclipse.

3.2) Add Struts2 dependencies, struts2 0 configuration dependencies, and JSON dependencies for STRUTS2:

<dependencies><!--struts2 Core-dependent--><dependency><groupid>org.apache.struts</groupid> <artifactid>struts2-core</artifactid><version>2.3.4</version><type>jar</type ><scope>compile</scope></dependency><!--struts2 0 Configuration dependent--><dependency>< groupid>org.apache.struts</groupid><artifactid>struts2-convention-plugin</artifactid>< Version>2.3.4</version><type>jar</type><scope>compile</scope></dependency ><!--struts2 JSON-dependent--><dependency><groupid>org.apache.struts</groupid>< artifactid>struts2-json-plugin</artifactid><version>2.3.4</version><type>jar</ Type><scope>compile</scope></dependency></dependencies>

Tested, there was no version-compatible bug in the dependencies above, not only because they were the same version, but because of how Maven was built automatically.

3.3) Configure Web. XML to 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, set some basic constants and applications:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE strutspublic "-//apache software foundation//dtd struts Configuration 2.0//en" "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><Packageextends=" Json-default, Struts-default "><!--Here you can set some global return value mapping relationships such as--></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 the action. It is set by not specifying convention, so for the Convention plug-in, the default is to treat all class names as action-terminated Java classes:

 Packagewatson.action;ImportJava.util.HashMap;ImportJava.util.Map;Importorg.apache.struts2.convention.annotation.Action;ImportOrg.apache.struts2.convention.annotation.Namespace;ImportOrg.apache.struts2.convention.annotation.ParentPackage;ImportOrg.apache.struts2.convention.annotation.Result;Importorg.apache.struts2.convention.annotation.Results; @ParentPackage ("Base") @Namespace ("/watson") @Results ({@Result (name= "JSON", type= "JSON", params={"root", "MSG"})}) Public classjsonaction {@Action (value= "JSON") PublicString json () {msg=NewHashmap<string, object>(); Msg.put ("Flag", "success"); Map<string, string> user =NewHashmap<string, string>(); User.put ("Name", "Zhang San"); User.put ("Age", "34"); Msg.put ("User", user);return"JSON";}//==================================PrivateMap<string, object>msg; PublicMap<string, object>getmsg () {returnmsg;}}

3.6) Deploy the project, launch the container, enter in the browser address bar: Http://localhost:7070/Struts2foo/watson/json. Wait until the results are as follows:

{"Flag": "Success", "user": {"Age": "the", "name": "Zhang San"}}

From the above results we know that after the 0 configuration is enabled, only the configuration in XML is reduced, and the annotations are made with annotation in each action instead. This removes the above configuration from the XML and writes the following code to the upper Jsonaction:

@ParentPackage ("base") @Namespace ("/watson"= "json", type= "JSON", params={"root", "MSG"})) 

Root is quite a parameter configuration in the XML configuration.

Four. Attached :

The return type of the action is JSON when the configurable parameter is detailed:

<result type= "JSON" ><!--here Specifies the property that will be Struts2 serialized, which must have a corresponding getter method-->< in the action!-- By default the value of all getter methods with return values is serialized, regardless of whether the method has a corresponding property--><param name= "root" >dataMap</param><!--Specifies whether to serialize empty properties-- ><param name= "Excludenullproperties" >true</param><!--here specifies that those properties in the Datamap will be serialized-->< param name= "includeproperties" >userList.*</param><!--here specifies that those attributes are to be excluded from the datamap, and the excluded properties will not be serialized. Generally does not appear with the upper parameter configuration at the same time--><param name= "Excludeproperties" >SUCCESS</param></result>

Reference:

1. "In-depth understanding of the principles and application examples of STRUTS2 return JSON data"

2. Summary of bugs when adding support packages: Http://hi.baidu.com/chennning/item/53d8f8b97c1fd5d985dd79de

3.jjiag22222 's Blog "HttpServletResponse in the PrintWriter need to pay attention to a small problem"

4.STRUTS2 0 Configuration Detailed: http://topic.csdn.net/u/20101130/11/a47de200-c0e2-4daa-841b-5b2cb659f66b.html?45426

Transferred from: http://kingxss.iteye.com/blog/1622455

Go Struts2 method Summary for returning JSON objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.