Springmvc solve the garbled in the corresponding

Source: Internet
Author: User

When the server returns Chinese, it does not use this annotation, but uses the HttpServletResponse object directly to complete the transmission, on the server side may pass Response.setcontenttype ("Text/plain;charset=utf-8 ") to set the encoding type so that there is no Chinese garbled

The return value is set according to its own data type, which is commonly used: 

response.setcontenttype ("text/html; Charset=utf-8 ");     HTML
response.setcontenttype ("Text/plain; Charset=utf-8 ");    Text
response.setcontenttype ("Application/json; Charset=utf-8 ");   Data
response.setcontenttype ("Application/xml; Charset=utf-8 "); Xml

Method Two can create a new class that implements the Beanpostprocessor

Import Java.nio.charset.Charset;  
Import java.util.ArrayList;  

Import java.util.List;  
Import org.springframework.beans.BeansException;  
Import Org.springframework.beans.factory.config.BeanPostProcessor;  
Import Org.springframework.http.MediaType;  

Import Org.springframework.http.converter.StringHttpMessageConverter; /** * Solve the Chinese garbled problem of @responsebody in spring MVC3 * * Public class Utf8stringbeanpostprocessor implements Beanpostprocess or {@Override public object Postprocessafterinitialization (object bean, String beanname) throws Beansexcep tion {if (bean instanceof Stringhttpmessageconverter) {MEDIATYPE mediatype = new mediatype ("TE    
          XT "," plain ", Charset.forname (" UTF-8 "));    
            list<mediatype> types = new arraylist<mediatype> ();    
           Types.add (mediatype);    
       ((Stringhttpmessageconverter) bean). Setsupportedmediatypes (types);    
    } return bean; } @Override   
   public object Postprocessbeforeinitialization (object bean, String beanname) throws Beansexception {Retu    
    RN Bean;  
 }    
}

Register this bean in the spring configuration file

<!--solve the use of @responsebody Chinese garbled. -->  
  <bean class= "Springmvc.extention.UTF8StringBeanPostProcessor" ></bean> 

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.