Spring MVC @ResponseBody Response Chinese garbled

Source: Internet
Author: User

Problem:
Chinese garbled problem occurs when the front end returns a string type of service through the GET Request server

Reason:
Because spring defaults to the string type's return encoding using the Stringhttpmessageconverter
>>> 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:
public static final Charset Default_charset = Charset.forname ("iso-8859-1");


Workaround:
Programme one:
Add annotations to methods that need to return a string, as follows: Effective only for a single method, not globally

@RequestMapping (value = "/getusers", produces = "application/json; Charset=utf-8 ")
Public String Getalluser () throws Jsongenerationexception, Jsonmappingexception, ioexception{
List < User > users = Userservice.getall ();
Objectmapper om = new Objectmapper ();
System.out.println (om.writevalueasstring (users));
DataGrid dg = new DataGrid ();
Dg.setdata (users);
Return om.writevalueasstring (DG);
}

Scenario Two:

Add in Spring-servlet.xml:

class= "Org.springframework.http.converter.StringHttpMessageConverter" ><property name= " Supportedmediatypes "value =" Text/plain;charset=utf-8 "/></BEAN></MVC:MESSAGE-CONVERTERS></MVC: Annotation-driven>

Programme III:
Rewrite a messageconverter, and then register to Annotationmethodhandleradapter

 PackageCom.h5.common.converter;ImportOrg.springframework.http.HttpInputMessage;ImportOrg.springframework.http.HttpOutputMessage;ImportOrg.springframework.http.MediaType;ImportOrg.springframework.http.converter.AbstractHttpMessageConverter;Importorg.springframework.util.StreamUtils;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportJava.nio.charset.Charset;Importjava.util.ArrayList;Importjava.util.List; Public classEncodingadapterextendsAbstracthttpmessageconverter < String > {     Public Static FinalCharset default_charset = Charset.forname ("UTF-8"); Private FinalCharset Defaultcharset; Private FinalList < Charset >availablecharsets; Private BooleanWriteacceptcharset;  PublicEncodingadapter () { This(Default_charset); }     PublicEncodingadapter (Charset defaultcharset) {Super(Newmediatype[]{NewMediaType ("text", "plain", Defaultcharset), mediatype.all});  This. Writeacceptcharset =true;  This. Defaultcharset =Defaultcharset;  This. Availablecharsets =NewArrayList (Charset.availablecharsets (). values ()); }     Public voidSetwriteacceptcharset (BooleanWriteacceptcharset) {         This. Writeacceptcharset =Writeacceptcharset; }     Public BooleanSupports (Class <?) >clazz) {        returnString.class==Clazz; }    protectedString readinternal (Class <?)extendsString > Clazz, httpinputmessage inputmessage)throwsIOException {Charset Charset= This. Getcontenttypecharset (Inputmessage.getheaders (). getContentType ()); returnstreamutils.copytostring (Inputmessage.getbody (), CharSet); }    protectedLong getcontentlength (String str, mediatype contentType) {Charset Charset= This. Getcontenttypecharset (ContentType); Try {            returnLong.valueof ((Long) Str.getbytes (Charset.name ()). length); } Catch(unsupportedencodingexception var5) {Throw Newillegalstateexception (VAR5); }    }    protected voidWriteinternal (String str, httpoutputmessage outputmessage)throwsIOException {if( This. Writeacceptcharset) {outputmessage.getheaders (). Setacceptcharset ( This. Getacceptedcharsets ()); } Charset Charset= This. Getcontenttypecharset (Outputmessage.getheaders (). getContentType ());    Streamutils.copy (str, CharSet, Outputmessage.getbody ()); }    protectedList < Charset >getacceptedcharsets () {return  This. Availablecharsets; }    PrivateCharset Getcontenttypecharset (mediatype contentType) {returnContentType! =NULL&& contenttype.getcharset ()! =NULL? Contenttype.getcharset (): This. Defaultcharset; }}

Registration Method One:

class class= "Com.ctrip.hotel.h5.common.converter.EncodingAdapter" ><constructor-arg index= "0" value= " UTF-8 "/></bean></util:list></property></bean>

Registration Method Two:
In the Webconfig.java:

@Override  Public void extendmessageconverters (listnew   Encodingadapter (); Converters.add (0, stringconverter);}

Programme IV:

Create a new class directly, and put in the code.

 PackageCom.h5.common.encode;Importorg.springframework.beans.BeansException;ImportOrg.springframework.beans.factory.config.BeanPostProcessor;ImportOrg.springframework.http.MediaType;ImportOrg.springframework.http.converter.HttpMessageConverter;ImportOrg.springframework.http.converter.StringHttpMessageConverter;Importorg.springframework.stereotype.Component;ImportOrg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;ImportOrg.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;ImportJava.nio.charset.Charset;Importjava.util.Arrays;Importjava.util.List;/*** Created by Xingyuzhu on 2017/2/27. * Resolves the problem of garbled characters in the response returned by @responsebody.*/@Component Public classEncodingpostprocessorImplementsBeanpostprocessor {@Override PublicObject Postprocessbeforeinitialization (Object bean, String beanname)throwsbeansexception{if(Beaninstanceofrequestmappinghandleradapter) {List< Httpmessageconverter <? >> Convs =( (Requestmappinghandleradapter) bean). Getmessageconverters ();  for(Httpmessageconverter <?) >Conv:convs) {                if(CONVinstanceofstringhttpmessageconverter) {(stringhttpmessageconverter) conv). Setsupportedmediatypes (Arrays.aslist (NewMediaType ("text", "HTML", Charset.forname ("UTF-8")))); }            }        }        if(Beaninstanceofrequestresponsebodymethodprocessor) {List< Httpmessageconverter <? >> Convs =( (Requestmappinghandleradapter) bean). Getmessageconverters ();  for(Httpmessageconverter <?) >Conv:convs) {                if(CONVinstanceofstringhttpmessageconverter) {(stringhttpmessageconverter) conv). Setsupportedmediatypes (Arrays.aslist (NewMediaType ("text", "HTML", Charset.forname ("UTF-8")))); }            }        }        returnBean; } @Override PublicObject Postprocessafterinitialization (Object bean, String beanname)throwsbeansexception{returnBean; }}

Programme V:
In our Webconfig.java, register a Bean: The method is defective Requestmappinghandleradapter other messageconverter is lost, causing other problems, such as returning a JSP page, will be hung off

@Bean PublicRequestmappinghandleradapter Requestmappinghandleradapter () {requestmappinghandleradapter reqMapHAdapter=NewRequestmappinghandleradapter (); ArrayList< Httpmessageconverter <? >> Msgconvs =NewArrayList < > (); Stringhttpmessageconverter Stringconverter=NewStringhttpmessageconverter (Charset.forname ("UTF-8"));    Stringconverter.setsupportedmediatypes (Arrays.aslist (Mediatype.text_plain));    Msgconvs.add (Stringconverter);    Reqmaphadapter.setmessageconverters (Msgconvs); returnReqmaphadapter;}

Programme VI:
In the Webconfig.java:

@Override  Public void extendmessageconverters (listNew  Stringhttpmessageconverter (Charset.forname ("UTF-8")); Converters.add (0, stringconverter);}

Scheme VII: (The coding of the tamper framework, recommended use)
In the Webconfig.java, tamper with the Stringhttpmessageconverter encoding method

@Override Public voidExtendmessageconverters (List < Httpmessageconverter <?) >>converters) {Httpmessageconverter Converter= Iterables.find (Converters,Newpredicate < Httpmessageconverter <? >>() {@ Override Public BooleanApply (@ Nullable Httpmessageconverter <? >input) {                returnInput! =NULL&& inputinstanceofStringhttpmessageconverter; }        }, NULL); if(Converter = =NULL) {Stringhttpmessageconverter stringconverter=NewStringhttpmessageconverter (); Stringconverter.setsupportedmediatypes (Arrays.aslist (NewMediaType ("text", "HTML", Charset.forname (UTF8))); Converters.add (1, Stringconverter);//The default Stringhttpmessageconverter in the second position        return; } stringhttpmessageconverter Stringhttpmessageconverter=(Stringhttpmessageconverter) converter; Stringhttpmessageconverter.setsupportedmediatypes (Arrays.aslist (NewMediaType ("text", "HTML", Charset.forname (UTF8) )));}

Spring MVC @ResponseBody Response Chinese garbled

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.