Some problems with @responsebody and how to solve them

Source: Internet
Author: User
Tags character set http request json string format
@ResponseBody & @RequestBody

@RequestBody annotations are used to read the contents of an HTTP request (string), and the Httpmessageconverter interface provided by SPRINGMVC converts the read content to JSON, Data in formats such as XML and bound to the parameters of the Controller method.
@ResponseBody the annotation is used to convert the object returned by the controller's method to the specified format by converting the Httpmessageconverter interface to data such as json,xml, etc., by response response to the client.
Because of the convenience of JSON passing information, there is much more to pass on JSON data.

Using @responsebody and @requestbody requires the introduction of two packages
JACKSON-CORE-ASL, and JACKSON-MAPPER-ASL.
Download Address: http://download.csdn.net/detail/czxt0605/7677923

You can convert a JSON-formatted string into a Java object, a string, in a controller.
Here is an example:

@RequestMapping ("/newdorminfo") public
@ResponseBody Info newdorminfo (@RequestBody info info) throws Exception {
        System.out.println (Info);
}
If you use these two annotations in a method of this controller, @RequestBody in the argument list you want to convert the JSON format data to the parameters of the corresponding Java object; @ResponseBody is placed in front of this method.
@Controller
@ResponseBody Public
class login{
    @RequestMapping ("/userlogin")   //Set the result encoding after response Public
    String Userlogin (httpservletrequest request,httpservletresponse response) throws exception{
}
If you want to return data in JSON format throughout the controller, you can write @responsebody annotations outside of the code body. Some of the problems I encountered

We learned that @ResponseBody can return data into JSON format, and today my classmates gave me the return data of the interface is jsonobj format, I was thinking, since String,java class objects can be converted to JSON format output, then this conversion is not more convenient. The code is as follows:

@RequestMapping ("/newdorminfo") public
@ResponseBody Jsonobject Getdorminfo (HttpSession session) {

        if ( Session.getattribute ("userid") = = null) {
            System.out.println (Studentutil.get_dormitory_info (StudentID, String.valueof (New Date (). GetTime ()), token));
            Return Studentutil.get_dormitory_info (studentid,string.valueof (New Date (). GetTime ()), token);
        return null;
    }
The return data type is set to Jsonobject, and the @responsebody annotation is used, but the error after running
Could not write Json:object is null (through reference chain:net.sf.json.jsonobject["XB"]->net.sf.json.jsonnull[" Empty "]); Nested exception is Com.fasterxml.jackson.databind.JsonMappingException:Object is null (through reference CHAIN:NET.SF . JSON. jsonobject["XB"]->net.sf.json.jsonnull["Empty"])
 //Google Translate comes
 Cannot write json:object to null (by reference chain: Net.sf.json.JSONObject ["XB"]-> Net.sf.json.JSONNull ["Empty"]); Nested exception is Com.fasterxml.jackson.databind.JsonMappingException:Object null (by reference chain: Net.sf.json.JSONObject ["XB"]-> Net.sf.json.JSONNull ["Empty"])
In the previous code through the printing know, first of all my data is not empty, then this problem in the nested exception, in the process of conversion error, that is, through the annotations to convert Jsonobject data into JSON format data failed, or that cannot be converted.

So I changed it. A return data type, string, however, another problem has been encountered, after replacing it with a string format, the data returned to the front end is actually in JSON format, but all of the Chinese have become question marks.
Disorder Touyi, check a lot of information but no, I return in a few ways before the data into the Utf-8 format, but after the front of the question mark, well.
Calm down to think, it will not be my problem, but @repsonsebody the problem, that is, no matter how I encode before returning, it will be re-encoded in return. I found the answer in this line of thought.

This can be said to be a bug,spring MVC of Spring MVC has a series of httpmessageconverter to deal with the return value of @responsebody annotations, If the return list uses Mappingjacksonhttpmessageconverter and returns a string, the Stringhttpmessageconverter is used. This convert uses a character set that is iso-8859-1 and final.

Citation: http://blog.csdn.net/hurryjiang/article/details/7710110

That, in other words, before returning, our data is encoded into a iso-8859-1 format, the front-end encoding format is inconsistent, resulting in garbled characters.
There are many solutions, and one blogger's solution is most simple and effective:

To solve the problem of returning Chinese garbled, there are two, the first is local, only for the return of a method of processing, the second is global, for the entire project, as follows:
The first: Add produces= "Text/html;charset=utf-8 in @requestmapping, such as:

@RequestMapping (value= "/login.do", method=requestmethod.post,produces= "Text/html;charset=utf-8")
    @ Responsebody Public
    String Login (@RequestParam (value= "username") string username, @RequestParam (value= "password String password) {
        return Jsonmessageutil.getsuccessjson ("login Successful");
    }
For the whole project of Chinese garbled problem resolution, please see the original blogger Link: Http://www.tuicool.com/articles/zeeQfe

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.