Springmvc the problem of garbled characters when using @responsebody output string and the solution

Source: Internet
Author: User
Emergence also encountered garbled problem, sometimes really feel that the English language of those areas is indeed very convenient, at least not for this classic trouble to toss.

There are many articles on the network that discuss garbled issues, because the different computer environments used by the authors are often not very comprehensive.
Here is a highly recommended article:
Http://dohkoos.name/java-garbled-analysis.html

In short, garbled "root cause is because the encoding and decoding are not the same code." For example, the author's example, using GBK encoding for UTF-8, using ISO-8859 decoding from UTF-8, can lead to garbled problems. This is like there is a Chinese article to Harry to see, but this article first translated into English by Zhang San, and then translated into Russian by John Doe (instead of translating back to Chinese), but Harry only understand Chinese, so the Muggle.

We need to keep coding or decoding both ends, and the character set conversion direction needs to be exactly the opposite: using GBK--and UTF-8 with UTF-8--and GBK. Since Java uses UTF-8 encoding, encoding and decoding are mediated by UTF-8.
For translation, is the first equivalent: the first translation of English, the corresponding decoding, in turn, is the English translation.

When you encounter garbled problems, the usual checks include:
1. The editor saves the character set of the file;
2. The character set of the database;
3. The application server or Web server handles the character set used by the string
4. JSP for character Set declaration
5. servlet filters, and the MVC Framework Interceptor for Character set processing
6. Other links related to character set processing

Check each link, unified press UTF-8 settings. I infer that the problem I have encountered falls under the 6th above.

Because it is the annotation @responsebody provided by SPRINGMVC to return a JSON string, and then parse the JSON on the client (now JSON as the data Interchange format looks more and more fashionable, the client I use more is Jqgrid or ExtJS).

The controller code is as follows:
Java code    @Controller    @RequestMapping ("/*")    public class  hellocontroller {       private transient final log log  = logfactory.getlog (hellocontroller.class);                @Autowired        private UserManager mgr =  null;               @RequestMapping (value= "Hello_ List.do ",  method = requestmethod.post)         @ResponseBody         public string hellolist ()  {            stringbuilder str = new stringbuilder ("{totalProperty:100,root:[") ;                       List<User> users = mgr.getusers ();           for   (user user : users)  {                str.append ("{id: "). Append (User.getid ());                str.append (",  name: '"). Append (User.getlastname ());                str.append ("',  descn: '"). Append (User.getfullname ()). Append ("'},");           }            str.append ("{id:4, name: ' 생활 ',  descn: ' Китай '}," );           str.append ("{id:5, name: ' Tchen8 ',  DESCN: ' Chinese '}]} ";                     &nbSp; log.info (Str.tostring ());                      return str.tostring ();        }     }  

In the spring configuration file, the default is as follows:
XML code <!--enables the Spring MVC @Controller programming Model--<mvc:annotation-driven/>

debugger, console output log see is Chinese, but the server-side sent string that is seen in Firebug is???? (in the case of an output such as "mouth port", it is necessary to first rule out whether the font of the system is missing), so it is judged that the character set is not the last time the server writes a string stream to the port.

By debugging the source code of spring, when declaring @responsebody, spring will go through annotationmethodhandleradapter to find the corresponding httpmessageconverter, We declare here that the returned type is a string, so it corresponds to Stringhttpmessageconverter. Through the experiment, I guess this stringhttpmessageconverter is the default string conversion work Class <mvc:annotation-driven/> triggered.

Unfortunately, the default character set used by Stringhttpmessageconverter is iso-8859-1
Java code ... public class Stringhttpmessageconverter extends Abstracthttpmessageconverter<string> {PU   Blic static final Charset default_charset = Charset.forname ("iso-8859-1"); ......

What we have to mention here is the class Mappingjacksonhttpmessageconverter with Stringhttpmessageconverter, who knows what the reason is: the same author, for these two classes, The default character set is Iso-8859-1, and one is UTF-8.

Now that this is the case, try to change the iso-8859-1 used in this place to UTF-8. There are two ways of thinking:
1. Replace the default character set;
2. Replace Stringhttpmessageconverter

Search for a bit, first see this solution:
http://forum.springsource.org/showthread.php?t=81858
What is provided here is to use a so-called configurablestringhttpmessageconverter instead of Stringhttpmessageconverter, The basic thinking technique is that because the default character set variables in Stringhttpmessageconverter are declared final and cannot be overridden directly by inheritance, copy the Stringhttpmessageconverter again. The constructor adds an input parameter that represents the character set, and then injects the UTF-8 into the configuration file by constructing the method. In the configuration file, this bean is declared in front of the <mvc:annotation-driven/>, so that it can be identified and injected before Stringhttpmessageconverter by spring.

But this approach is somewhat foolhardy, based on a version of it that simplifies it by inheriting stringhttpmessageconverter, then injecting the character set configuration we want in the subclass:
Java code public class Mystringhttpmessageconverter extends Stringhttpmessageconverter {public Mystringhttpmessag           Econverter (Charset defaultcharset) {list<mediatype> mediatypelist = new arraylist<mediatype> ();           Mediatypelist.add (New mediatype ("text", "plain", Defaultcharset));           Mediatypelist.add (Mediatype.all);       Super.setsupportedmediatypes (mediatypelist); }          }

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.