Brief analysis of Spring MVC data parsing

Source: Internet
Author: User

Brief analysis of Spring MVC data parsing
Special Note: This article uses the spring version of 4.1.3
Common Data Submission methods:
1. Form Forms Submit Data
1.1 parsing Form form data (no images, etc.)
Front-End Code examples:

<form action="test/entity"method="post">            type="text" name="userid"/><br>            type="text" name="username"/><br>            type="submit"value="提交"/></form>

Background code example:

@Controller@RequestMapping("/test") Public  class testcontroller extends basecontroller{    Private Static FinalString SIGNATURE ="San-signature";Private Static FinalString KEY ="San-key";@RequestMapping(value="/entity", method={requestmethod.get,requestmethod.post}) Public@ResponseBodyvoid Useentey(@ModelAttribute user user) {System.out.println ("[Entity] User information:"+user.tostring ()); }...

Note: When using @ Modelattribute annotations require that the user entity class has init otherwise it will error, parameters can not be resolved.
User entity Class Code:

 Public classUser {PrivateString userid;PrivateString username; PublicStringGetUserid() {returnUserID } Public void Setuserid(String userid) { This. UserID = userid; } PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } Public User(){};//Require init    / * No person will report error no default constructor found; nested exception is java.lang.nosuchmethodexception:com.inphase.sandyagor.u Ser.entity.user.<init> () */     Public User(String userid,string username) { This. Userid=userid; This. username=username; } @Override PublicStringtoString(){returnString.Format ("{\" userid\ ": \"%s\ ", \" Username\ ":%s}", UserID, username); }}

Run Show:

We can use the grab Bag tool to see the requested format type:

Validation results:

2. Ajax Submission Data
2.1 General Format
Front-End Part code:

<html>  <head>    <base href="<%=basePath%>">    <title>Test page</title>    <script src="Js/jquery.min.js" ></script>    <script type="Text/javascript">         function submit(){                varUserID = $ ("#userid"). Val ();varUsername = $ ("#username"). Val (); $.ajax ({URL:"Test/entity", type:"POST", DataType:"JSON", data:{"userid": UserID,"username": username}, Success: function(JR){alert (JR.responseData.message); }, Error: function(JR){alert (JR.responseData.message); }, Fail: function(){Alert"System-level Error! ");            }                }); }</script>  </head>  <body>  <hr Color="green">Ajax Submission Data<br>User id:<input type="text" id="userid"/><br>User name:<input type="text" id="username"/><br>  <input type="button" value="Submit" onclick ="Javascript:submit ();" >   <hr Color="Red">...

Tips for the front end: Ajax datatype
Requires a parameter of type string that expects the data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter.
The following types are available:
XML: Returns an XML document that can be processed with jquery.
HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
Script: Returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note When you make a remote request (not under the same domain), all post requests are converted to get requests.
JSON: Returns the JSON data.
JSONP:JSONP format. When a function is called using the Sonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function.
Text: Returns a plain text string.
Back-end Section code:

@Controller@RequestMapping("/test") Public  class testcontroller extends basecontroller{    Private Static FinalString SIGNATURE ="San-signature";Private Static FinalString KEY ="San-key";@RequestMapping(value="/entity", method={requestmethod.get,requestmethod.post}) Public@ResponseBodyvoid Useentey(@ModelAttribute user user)throwsexception{System.out.println ("[Entity] User information:"+user.tostring ()); Writerjson (true,"","The request was successful! "); }

Results show:
Front page:

Click Effect:

We also use the grab Bag tool to grab the request type:

You can see that the data format submitted with the form form has been, and the request address is the same
3. Comparison of common analytic methods
In the background parsing aspect, this time can use the common analytic method also can parse:
Case code:

@RequestMapping(value="/common",method={RequestMethod.GET,RequestMethod.POST})    publicvoiduseCommon() throws Exception{        new User(                this.getRequest().getParameter("userid"),                this.getRequest().getParameter("username"));        System.out.println("[common]用户信息:"+user.toString());        WriterJson(true,"","请求成功!");    }

These two analytic ways are different, in the actual project, see a person likes.
4. Specifying Content-type submission data (Ajax)

contentType"application/json"

Even if you specify the format of the Content-type, the above 3 method can still parse the submitted data, here do not repeat. Here is a @requestbody to parse
Front-End Code:

<html>  <head>    <base href="<%=basePath%>">    <title>Test page</title>    <script src="Js/jquery.min.js" ></script>    <script type="Text/javascript">         function submit(){                varUserID = $ ("#userid"). Val ();varUsername = $ ("#username"). Val (); $.ajax ({URL:"Test/json", type:"POST", DataType:"JSON", ContentType:"Application/json", data:{"userid": UserID,"username": username}, Success: function(JR){                        varmessage = JR.responseData.message; Alert"Success:"+message); }, Error: function(JR){                        varmessage = JR.responseData.message; Alert"failed:"+message); }, Fail: function(){Alert"System-level Error! ");            }                }); }</script>  </head>  <body>  <hr Color="green">Ajax Submission Data<br>User id:<input type="text" id="userid"/><br>User name:<input type="text" id="username"/><br>  <input type="button" value="Commit" onclick=" Javascript:submit (); " >   <hr Color="Red">...

Back-end parsing:

@RequestMapping(value="/json",method={RequestMethod.GET,RequestMethod.POST})    publicvoiduseJson(@RequestBody Map<String,Object> userinfo) throws Exception{        System.out.println("[json]用户信息:"+userinfo);        WriterJson(true,"","请求成功!");    }

Results show:

We also capture the package to show:

Back-end output:

In the background parsing, we can still use the method of entity to parse the parameter
Code:

@RequestMapping(value="/jsonEntity",method={RequestMethod.GET,RequestMethod.POST})    publicvoiduseJsonEntity(@RequestBody User user) throws Exception{        System.out.println("[jsonEntity]用户信息:"+user.toString());        WriterJson(true,"","请求成功!");    }


Description, the JSON format can automatically encapsulate the entity type, which is available in the Spring 3.x version.

To use the test page: http://localhost:8080/sandyagor/test/show
According to your project name and access address
Full Demo
The project uses spring MVC 4.1.3
Log using log4j
Development tools: MyEclipse 10,JDK 1.7
Development environment: Win7 (64-bit)
Development server: Tomcat 7.0.68
Database: Reserved MySQL connection, master-slave connection
In case of problems can contact QQ 605251685

Brief analysis of Spring MVC data 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.