SPRINGMVC Accept JSON parameter details and common error summary I changed it.

Source: Internet
Author: User
Tags object object

SPRINGMVC accepts JSON parameters and summarizes common mistakes

I don't want to use it for a long time, Session I want to feel the Token safe and steady way, and write a unified interface to the browser and the app. So the front desk of a practiced hand project Ajax has been changed to, jump and use SpringMVC control and forwarding. For transmitting JSON data there is some deeper understanding and sharing, please correct me.

In the SpringMVC we can choose a number of ways to accept, JSON SpringMVC before we say how to accept JSON , we first talk about what is JSON . I don't have to go into specific definitions, in which JavaScript we often define JSON objects

var jsonobject = {"username": "admin","password": 123}

In this form, we call it a JSON object , and there is a concept called a JSON string , a string, as the name implies, a whole that is wrapped up by ' or ', which we call a string. We know that the string can be output directly, and the object cannot be output directly. So in JavaScript, we can

// defines an object Jsonobject var jsonobject = {"username": "admin","password": 123};alert (jsonobject);

At this point, [Object Object] is displayed without outputting the contents of the JSON object , and JavaScript provides us with two tools

Json.parse ()
Used to convert a JSON string to a JavaScript object.
Json.stringify ()
Used to convert JavaScript values to JSON strings.

So when we enter

Alert (Json.stringify (Jsonobject));

It will display {"username": "admin", "Password": 123};

* Okay, here's the tutorial on JSON. Let's talk about Springmvc.

The first method of transmitting JSON data:

Since JSON has these two ways of being, what do we do when we pass the value of Ajax to SPRINGMVC?
We first try to send the JSON object directly

1 //Defining JSON Objects2             varUsername = $ ("#username"). Val ();3             varPassword = $ ("#password"). Val ();4             varJSON = {5"Username": Username,6"Password": Password7             };8 9 //Jquery Ajax RequestTen $.ajax ({ OneURL: "Jsontest", AType: "POST", -Async:true, - Data:json, theDataType: ' JSON ', -Success:function(data) { -                     if(Data.userstatus = = = "Success") { -$ ("#errorMsg"). Remove (); +}Else { -                         if($ ("#errorMsg"). Length <= 0) { +$ ("Form[name=loginform")). Append (errormsg); A                         } at                     } -                 } -});

Let's start by thinking about what SPRINGMVC has to offer us, there is a @requestparam annotation, and for this annotation, its role Servlet request.getParameter is basically the same as ours. We first use this annotation to get

1   @RequestMapping ("/jsontest")2public     void Test (@RequestParam (value= " Username ", required=true) String username,3     @RequestParam (value=" Password ", Required=true) String password) {4         System.out.println ("username:" +  username); 5         System.out.println ("Password:" + password); 6     }

Background successful output of our parameters, successfully accepted!

Springmvc so smart, what happens if we remove the @requestparam annotation and put two values directly?

1 @RequestMapping ("/jsontest")2public     void  Test (String username,string password) {3         System.out.println ("username:" + username); 4         System.out.println ("Password:" + password); 5     }

even if the same success , the principle I do not more than repeat here, interested friends can break point to see.

above is the first method of transmitting JSON format data to the background, the key is two points :

1, The foreground is a JSON object . (I think it's possible to pass a JSON string, not yet tested.)

at the same time, Ajax can never write contentType: "Application/json",

"Do not write is the default jquery using the default application/x-www-form-urlencoded type"

2, in the controller of Java can use this @RequestParam

You can also write nothing and receive it directly with a string parameter . but you never write @requestbody .

————————————————————————————————————————————————

The second way to pass JSON data to the background:

SPRINGMVC provides a @requestbody, which is used to handle data sent from the foreground definition Content-Type : not application/x-www-form-urlencoded encoded content,

such as Application/json, application/xml, etc.;


Careful friends may have discovered that in previous Ajax we did not define the type of Content-type , and jquery uses the application/x-www-form-urlencoded type by default.

So that means the @requestparam annotation of Springmvc, the request.getparameter of the servlet is acceptable to JSON objects transmitted in this format.

Why not!? Get request Presumably everyone is not strange, it will be the parameter url?username= "admin" &password=123 this way to the server, And Request.getparameter can receive this parameter, we can also see this in the browser address bar.

And we use the POSTof Ajax, and send the JSON object, then how to get the background?

The answer is that this Content-Type x-www-form-urlencoded encoding converts JSON data into a string,(username= "admin" &password=123) Then add this string to the URL, with the? Split, (is not like the Get method), submitted by POST , the browser encapsulates the data into the HTTP body, and then sent to the server. So it does not appear on the URL. (This paragraph may be a bit around the mouth, I hope you understand carefully.) )


Finally finished, long to breathe. So when we use @requestbody annotations, the foreground content-type must be changed application/json to, if not changed, the front desk will error 415 (unsupported Media Type). The background log will be error Content type ' application/x-www-form-urlencoded;charset=utf-8 ' not supported, These errors are not displayed with the error message in Eclipse under Tomcat, only use the log to display, how to configure the log you can read my previous article.

Next we configure it correctly, it says that Content-type needs to be changed, and our data is changed, and this annotation only accepts JSON strings instead of JSON objects

1 $.ajax ({2URL: "Jsontest",3Type: "POST",4Async:true,5ContentType: "Application/json",6 data:JSON.stringify (JSON),7DataType: ' JSON ',8Success:function(data) {9                     if(Data.userstatus = = = "Success") {Ten$ ("#errorMsg"). Remove (); One}Else { A                         if($ ("#errorMsg"). Length <= 0) { -$ ("Form[name=loginform")). Append (errormsg); -                         } the                     } -                 } -});

The background also changes, json can actually be understood as a key value pair, so we use map to receive , and then the string or other data types for further processing.

 1  @RequestMapping ("/jsontest"  Span style= "COLOR: #008080" >2  public  void< /span> Test (@RequestBody (Required=true ) Map<string,object> map" { 3  String username = map.get ("username" ). ToString ();  4  String password = map.get ("password"  5  System.out.println ("Username:" + username); 6  System.out.println ("Password:" + password) ; 7 } 

"Less data can be received in map or in the original entity class by adding a temporary (just for receiving parameters and not manipulating the database) member variables to receive"

At the same time, I think of the magical springmvc, so I decided to remove the annotations to try, OK, decisive was exploded a null pointer error ... Try to stop this.


SPRINGMVC also provides methods for parameter direct and Pojo binding, let's try it out. The receptionist was very friendly.

@RequestMapping ("/jsontest")    publicvoid  Test (@RequestBody User user  ) {         = user.getusername ();         = User.getpassword ();        System.out.println ("username:" + username);        System.out.println ("Password:" + password);    }

OK, this time can be taken to the value of , I personally for this kind of small data upload, I do not like this method, the user has a lot of variables, I only use two of them, there is no need to create a user object, When the general data is small, I prefer to use a separate value. We think again, if it is in the case of uploading JSON objects , we can bind Pojo, the answer is yes, do not use @requestparam annotations, otherwise you will report an Required User parameter ‘user‘ is not present error. The basic end of this explanation, the following to summarize.

above is the second method of transmitting JSON data to the background, the key summary is two points :

1, when we use @requestbody annotations in the background,

The foreground Ajax sends the request, must add contentType: "Application/json",

and     json.stringify (JSON) must  never be a JSON object {}

2, at this time the backstage controller must use @requestbody annotation

3, add the 3rd place to note:

If the background is annotated with @requestbody, this requires that the foreground Ajax must be used

ContentType: "Application/json"

, a 400 error is reported when the same request passes a number of other type parameters, such as string arguments, in addition to passing the JSON type. This is a mishap, in this way, the controller layer method can only receive a JSON-type parameter, no longer have other types of parameters.

    • We first talked about JSON objects and JSON strings.
    • And then said SPRINGMVC accept two JSON formats, the front-end contenttype settings, and the backend whether to use annotations to accept, but also mention a little servlet.

  • When Ajax uploads in application/x-www-form-urlencoded format, the JSON object is used, and the background needs to be obtained using the @requestparam or servlet. When Ajax uploads in Application/json format, the JSON string is used, and the background needs to be obtained using @rquestbody.

This is my experiment for a day of some summary, hope can help everyone, if there are errors, please haihan and correct.

SPRINGMVC Accept JSON parameter details and common error summary I changed it.

Related Article

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.