STRUTS2 result returns the JSON object's detailed _java

Source: Internet
Author: User
Tags extend package json rar

If it is the client's Http+json interface project, the use of Jersery framework development is absolutely the first choice without JSP and other view views. In the architecture based on SPRING3 MVC, 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 servlet's output stream, 2. Use STRUTS2 to extend the JSON.

I. Using the servlet's output stream

The essence of the JSON interface is that JSON data is passed in a normal JSON-formatted string, and the so-called "JSON object" refers to the result of parsing and wrapping the JSON string.

So here you just write a JSON-formatted string to the servlet's HttpServletResponse, which uses the printwriter approach, and of course the stream stream. Note that the encoding is not set before the call to Getwriter (both the setContentType or the Setcharacterencoding method set encoding), and HttpServletResponse returns a default encoding ( ISO-8859-1) encoded PrintWriter instance. This will result in Chinese garbled. And the encoding must be set before calling Getwriter, otherwise it is invalid.

  To write the interface code:

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

public void Write () throws ioexception{ 
 HttpServletResponse response=servletactioncontext.getresponse (); 
 * * No encoding is set before calling Getwriter (both setContentType or Setcharacterencoding method setting encoding), 
 * HttpServletResponse returns a PrintWriter instance encoded with the default encoding (both iso-8859-1). This will 
 cause 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 pass, where a simple concatenation is done to test 
 string jsonstring= "{\" User\ ": {\" id\ ": \" 123\ ", \" name\ ": \" john \ ", \" say\ ": \ "Hello, I am a action to print a json!\", \ "password\": \ "json\"},\ "success\": true} "; 
 Out.println (jsonstring); 
 Out.flush (); 
 Out.close (); 
}

  Configure action

It is obvious from the following configuration that the configuration does not differ from the normal action configuration, except that the view is not returned.

 
 

  return value

 
 

Two. Using STRUTS2 to extend JSON

You will definitely need to add a support package to use this extension feature. 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 the above version, because xwork-core-*. There are no Org.apache.commons.lang packages in the 2.2.1 and above versions of the jar. When you start 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 this support way, that needs 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. Xwork-core-*.jar's 2.2.1 version is found in the class and not in Xwork-core-2.1.6.jar.

Finally, because the original construction method and Non-stop Wade Ray, really not worth, really tired. Using automation artifacts such as Maven will largely avoid bugs that rely on version differences between packages. In section III, the "STRUTS2 0 Configuration" uses the Maven widget approach.

  Writing Interface Code

The JSON () method in this class is a common Struts2 method. There are no 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 modifier will be included in the JSON string returned to the client. To remove attributes that do not need to be included, you need to annotate using @json (Serialize=false) on the getter method in the class structure, but you can also remove the getter method directly without affecting other businesses. So the return result in this example is a JSON-formatted string that converts the Datamap object.

 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 PM 06:21:01 * * public class Jsonaction extends Actionsupport 
 
 {private static final long serialversionuid = 1L; 
 Private map<string,object> Datamap; 
 
 Private String key = "Just";  
 The data in public String JSON () {//Datamap will be converted to a JSON string by STRUTS2, so here's the first to clear the data Datamap = new hashmap<string, object> (); 
 User user = new user (); 
 User.setname ("John"); 
 User.setpassword ("123"); 
 Datamap.put ("user", user); 
 Put in a successful identifier datamap.put ("Success", true); 
 Returns the result return SUCCESS; 
 Public map<string, Object> Getdatamap () {return datamap; 
 }//Set the key property not to be returned as JSON content @JSON (serialize=false) public String Getkey () {return key; } 
 
} 

  Configure Aciton

In the configuration, you first need to inherit json-default from the package where the action resides, or the inherited parent package inherits Json-default. This configures the return type of the action as JSON, and can configure some class parameters such as its serialized attributes

<?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 "class=" JSON. Jsonaction "method=" JSON > 
 <result type= "JSON" > 
 <!--Specify the properties that will be Struts2 serialized. The attribute must have a corresponding getter method in the action--> 
 <param name= "root" >dataMap</param> 
 </result> 
 </action> 
 </package> 

  return value

 
 

Three. Struts2 0 Configure the use method, using the Maven widget:

3.1 Create a WebApp, or use MAVEN to build, build process Reference Limingnihao Blog: Use Eclipse to build Maven Springmvc project.

3.2 Add Struts2 dependencies, struts2 0 configuration dependencies, and struts2 JSON dependencies:

 <dependencies> <!--struts2 core dependencies--> <dependency> <groupid>o Rg.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> <groupi D>org.apache.struts</groupid> <artifactId>struts2-json-plugin</artifactId> <version> 2.3.4</version> <type>jar</type> <scope>compile</scope> </dependency> </DEP Endencies> 

After testing, there is no version-compatible bug between the dependencies above, not only because they are the same version, but because of the way Maven is built automatically.

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/" 
Java ee " 
 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> 

3.4 Configure Struts.xml, 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 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" 
 1073741824 "/> 
 <constant name= struts.devmode" value= "false"/> 
</struts>

3.5 Write and configure the action. Set by not specifying convention, so for the Convention plug-in, the default is to treat all class names as action-terminated Java classes:

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.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", "John"); 
 User.put ("Age", "34"); 
 Msg.put ("user", user); 
 return "JSON"; 
 
 //================================== private map<string, object> msg; 
 Public map<string, Object> getmsg () {return msg; 

 } 
 
}

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

 
 

From the results above, after the 0 configuration is enabled, there is only less configuration in the XML, annotated with annotation in each action instead. Here, remove the configuration above in XML, and write the following code to the top of the upper 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.

Four. Attach:

An explanation of the configurable parameters for the action's return type is JSON:

<result type= "JSON" > 
 <!--Specifies a property that will be Struts2 serialized, which must have a corresponding getter method in the action--> 
 <!-- The default will be to sequence all the values of the Getter method with the return value, regardless of whether the method has a corresponding property--> 
 <param name= "root" >dataMap</param> 
 <!-- Specifies whether to serialize null properties--> 
 <param name= "excludenullproperties" >true</param> 
 <!-- This specifies that those attributes in the Datamap will be serialized--> 
 <param name= "includeproperties" >userList.*</param> 
 <!-- This specifies that those attributes will be excluded from the datamap, that these excluded properties are not serialized, and that the--> 
 <param name= "excludeproperties" is not normally present at the same time as the top parameter configuration. /param> 
</result>

Attachment download

Strutsjson.rar

Struts2foo.rar

The above is Struts2 returns the whole content of the JSON object, hope can give everybody a reference, also hope everybody support cloud habitat community a lot.

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.