Struts2 action receive POST request JSON data and its implementation parsing

Source: Internet
Author: User

Tag: ORM load via color default ADE message HTML server

I. Understanding JSON

JSON is a lightweight, text-based, language-independent data interchange format that can be used to store or represent structured data in the form of a text format.

Two. Post request and Content-type:application/json

Common HTTP request methods are get, POST, PUT, delete and so on. When the POST request is submitted, the request data is placed in the body of the message, and the format and encoding of the request data are specified with Content-type. such as our commonly used form <form> submit, its content-type default is application/x-www-form-urlencoded, the submitted data is encoded according to Key1=val1&key2=val2, The K-v value can also be easily parsed by the server side.

The advent of JSON allows the exchange of data to be no longer confined to simple k-v structures, but can have more complex hierarchies, especially for restful interfaces. When sending a request, specify Content-type as Application/json to use the JSON string as the requested data. When the request is received on the server side, the request data is processed according to the JSON string.

Three. STRUTS2 receive JSON request

Extracting the post parameters of Content-type as application/x-www-form-urlencoded in Struts2 action is very familiar: Define attributes in action and their getter, setter methods, When a request is received, the property is assigned the parameter value with the same name as the property by default.

However, for the request data of Content-type Application/json, Struts2 cannot be resolved by default. Because the requested JSON data needs to be read from the input stream, it cannot be parsed directly from the ServletRequest request parameter. It is therefore easy to think that the most straightforward way to read JSON request data is to read from the input stream. The Struts2 Strus2-json-plugin also provides interceptors to parse JSON request data. The following two scenarios are analyzed:

1. Read the JSON request data from the input stream, here is a way to read the input stream data implemented in the action

1     //parse the requested JSON data2     PrivateString Getrequestpostdata (HttpServletRequest request)throwsIOException {3         intContentLength =request.getcontentlength ();4         if(contentlength<0){5             return NULL;6         }7         byteBuffer[] =New byte[contentlength];8          for(inti = 0; I <contentlength;) {9             intLen = Request.getinputstream (). read (buffer, I, contentlength-i);Ten             if(len = =-1) { One                  Break; A             } -i + =Len; -         } the         return NewString (buffer, "Utf-8"); -}

The method is called in the Execute method of the action to get the JSON data to the request.

2. Using Struts2-json-plugin Configuration

    • To add a dependency of Struts2-json-plugin, take MAVEN configuration as an example:
<Dependencies>   ...   <Dependency>       <groupId>Org.apache.struts</groupId>       <Artifactid>Struts2-json-plugin</Artifactid>       <version>Struts_version</version>   </Dependency>   ...</Dependencies>
    • Struts.xml configuration file Add JSON configuration (Bold section)
<name= "Example"  extends= "Struts-default,Json-default ">    ...      <name= "json"/>  </package>      
    • Specify the JSON data in the action of each key and getter, setter, such as the requested JSON data as follows, then define in action named type, message, code property and its getter, setter
{    "type": Ten,    "message": "This is a test msg",    "code":

Thus, when the above JSON request data is received, struts defaults to parsing the value of type, message, and code.

Analysis of 3.struts2-json-plugin parsing JSON request data

After analysis, Struts2-json-plugin parse JSON request data, one of the core classes is the Jsonintercepter class. The main task of this interceptor is to read the JSON request data, extract the JSON data out of the K-V value and set it to the action's properties. The steps are as follows:

    • Determines whether the current request data type is a JSON type
1 String contentType = Request.getheader ("Content-type"); 2 ... 3 if null) && contenttype.equalsignorecase ("Application/json")) {4     //  load JSON Object5     Object obj = jsonutil.deserialize (Request.getreader ()); 6     ... 7 }
    • If the data type is JSON and the JSON data is read from the input stream, the following is the deserialize method of the Jsonutil class
1      Public StaticObject Deserialize (reader reader)throwsjsonexception {2         //Read Content3BufferedReader Bufferreader =NewBufferedReader (reader);4 String Line;5StringBuilder buffer =NewStringBuilder ();6 7         Try {8              while(line = Bufferreader.readline ())! =NULL) {9 Buffer.append (line);Ten             } One}Catch(IOException e) { A             Throw Newjsonexception (e); -         } -  the         returnDeserialize (buffer.tostring ()); -}
    • After parsing the JSON object, traverse the JSON object, remove the k-v, and give K the same properties by the V setting of the reflection

Developers can choose according to their needs: Read JSON request data directly from the input stream, or use Struts2-json-plugin to process the JSON request data.

Resources:

Four common methods of POST submission data (https://imququ.com/post/four-ways-to-post-data-in-http.html)

JSON Plugin (https://struts.apache.org/docs/json-plugin.html)

Struts2 action receive POST request JSON data and its implementation parsing

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.