SPRINGMVC Configuration One: Ajax requests to prevent the return of Chinese garbled configuration instructions

Source: Internet
Author: User

The role of the Spring3.0 MVC @ResponseBody is to write the return value directly into the HTTP response body.

Spring uses Annotationmethodhandleradapter's Handleresponsebody method, annotationmethodhandleradapter using the request Header " The value of accept "matches the mediatype supported by Messageconverter and then writes the response" Content-type "with the first value of" accept ". General requests are made through the browser, and the value of "Accept" in the request header is generated by the browser.

Someone tracking @ResponseBody Implementation class found its default encoding is iso-8859-1,

Workaround, manually configure the Bean in the Spring MVC configuration file:
<!--start the SPRINGMVC annotation function, complete the request and annotation pojo mappings--
<beanclass= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<propertyname= "Messageconverters" >
<list>
<bean class = "Org.springframework.http.converter.StringHttpMessageConverter" >
<property name = "Supportedmediatypes" >
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

This specifies the encoding by configuring the Annotationmethodhandleradapter Class Messageconverters property.
Remember that you need to add the bean part to the <context:component-scanbase-package= "Com.zlscw.mvc"/> Front,

This makes it possible to call directly in jquery without garbled characters.

-------------------------------------------This article is pretty much in place.

Recently with Spring3 's MVC write things, deeply its webwork/struts2 convenience, but in through @responsebody this annotation output a JSON string, The text characters in the JSON string found on the page have been garbled. Through the Firefox observation of the returned string, the Chinese part of all become the??????? The form of the initial decision is to return when the spring processing @responsebody uses the wrong encoding.

Because I have already configured spring's Characterencodingfilter in Web. XML and have forced the encoding of request and response to be specified as Utf-8, the reason for garbled is certainly the logic somewhere inside spring.

Tune the output level of spring in log4j to debug by accessing the problematic address and discovering that spring is handling the annotation of @responsebody. Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter used the org.springframework.http.converter.String Httpmessageconverter to deal with it, then opened the spring source code to see what the class actually did.

Don't look it doesn't matter, a look startled, inside unexpectedly is this defines its default encoding:

1publicstaticfinalcharsetdefault_charset = Charset.forname ("iso-8859-1");

Suddenly heart born n kind of uncomfortable: the spring, unexpectedly still in which Western European character set as its default code, Pit Daddy Ah! (In many spring classes, the coding is already utf-8, such as the mappingjacksonhttpmessageconverter that is responsible for the JSON view, which is the default use of UTF-8). Originally wanted to directly modify the source of spring to repackage a jar out, and later see Spring's Javadoc found that The Getdefaultcontenttype method in the parent class Org.springframework.http.converter.AbstractHttpMessageConverter can be overridden:

By default, this is returns the first element of Thesupportedmediatypes property, if any. Can be overridden insubclasses.

Thought this is simple, your default_charset is not final? Then I inherit one out, according to my needs defined as utf-8? The code is as follows:

01 PublicclassUtf8stringhttpmessageconverterextendsStringhttpmessageconverter {02 03PrivateStaticFinalMediaTypeutf8 =NewMediaType ("text", "plain", 04charset.forname ("UTF-8")); 05PrivateBooleanwriteacceptcharset=true; @Override08protectedMediaType Getdefaultcontenttype (stringdumy) {09returnUTF8; 10} 11 12protectedList Getacceptedcharsets () {13returnArrays.aslist (Utf8.getcharset ()); 14} 15 16protectedvoidWriteinternal (Strings, httpoutputmessage outputmessage) 17throwsIOException {18if( This. Writeacceptcharset) {19outputmessage.getheaders (). Setacceptcharset (Getacceptedcharsets ()); Charset Charset = Utf8.getcharset (); 22filecopyutils.copy (s),NewOutputStreamWriter (Outputmessage.getbody (), 23charset)); 24} 25 26 PublicBooleanIswriteacceptcharset () {27returnWriteacceptcharset; 28} 29 30 PublicvoidSetwriteacceptcharset (BooleanWriteacceptcharset) {31 This. Writeacceptcharset = writeacceptcharset;32} 33 34}

Then, add the following bean declaration in the spring configuration file, replacing the original stringhttpmessageconverter with the class you wrote:

1"Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >2 " Messageconverters "> 3 4" Utf8stringhttpmessageconverter"class=" Xxx.xxx.UTF8StringHttpMessageConverter "/>5 6 7

Then look at the JSON string returned by @responsebody, and finally the Chinese can be displayed normally.

-------------------------------------------here are some explanations

However, we generally return the result of a string or byte[] Type on the method labeled @responsebody, and the expected value of "content-type" should be "Text/plain" or "Application/octet-stream".
This causes the browser to not handle the returned content correctly.
In fact, spring in the process of processing with Httpmessageconverter will first determine whether Responseheader is written "Content-type", if not written, will use Requestheader "Accept The first value.
But since spring encapsulates httpservletresponse, it actually uses servletserverhttpresponse, a class that has a reference to the real httpservletresponse.
The process of judging Responseheader is using the Servletserverhttpresponse getheaders () method, but the method does not return the header in the true HttpServletResponse. (This should be a problem, right?) )
So although we can add a reference to the HttpServletResponse in the controller's method, and then set the value of "Content-type", it does not work.
To handle @responsebody, which then uses some httpmessageconverter to process the information specifically.
Chrome generates a value of application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,**
So the value of "Content-type" in the last write to response is "application/xml" or "application/x-ms-application".

-------------------------------------------------actually this annotation can not be used, directly using response to write to the output stream.

Return JSON using jquery Ajax calls, Chinese garbled problem

Jquery:

$.ajax ({
URL: '/test/testaction.do?method=test ',
Type: ' POST ',
DataType: ' JSON ',
timeout:5000,
Async:false,
Error:function () {
Alert (' Get Data failed! ‘);
},
Success:function (JSON) {
Jsobject = Eval_r (JSON);
}
});
return jsobject;

Jsonarray JSON =jsonarray.fromobject (syslist);//syslist is a list
Set response contenttype to solve Chinese garbled characters
Response.setcontenttype ("Text/html;charset=utf-8");
Response.getwriter (). Print (json.tostring ());
return null;

SPRINGMVC Configuration One: Ajax requests to prevent the return of Chinese garbled configuration instructions

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.