SpringMVC solves three methods for garbled ajax requests: springmvcajax

Source: Internet
Author: User

SpringMVC solves three methods for garbled ajax requests: springmvcajax

SpringMVC solves the problem of garbled ajax requests

Preface:

Recently, the springmvc project was used in the project. data can be displayed normally in the Request Method on the returned page, but garbled characters are always displayed for ajax requests. First, the first one is because we have configured spring character encoding filters in web. xml. Why can't we use ajax requests? The following is a simple analysis for your reference only.

First, list simple request codes:

Browser:

<script type="text/javascript">$.ajax({    type: "POST",    url: "/pages/ajax",    data: "name=garfield&age=18",    success: function(data){      console.log(data);   }  })</script>

Server:

@ ResponseBody @ RequestMapping ("/ajax") public String ajaxCharacter () {return "test ";}

Web. xml:

<Filter> <filter-name> characterEncodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <! -- For request --> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init-param> <init-param> <! -- For response --> <param-name> forceEncoding </param-name> <param-value> true </param-value> </init-param> </filter>

First, when a request arrives, it will first pass through the spring filter CharacterEncodingFilter. After the filter is encoded, it will enter the DispatcherServlet of springmvc, using a series of springmvc transformations (omitted here ...), Reach our control layer and help us encapsulate the parameters. After configuring this configuration item in springmvc <mvc: annotation-driven>, RequestMappingHandlerAdapter and HttpMessageConverter are configured by default. When @ ResponseBody is used, this data converter is called when data is returned. After viewing the source code can be seen, by default will be converted to the ISO-8859-1 format. Simple source code attachment:

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {  public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");  private final Charset defaultCharset;  private final List<Charset> availableCharsets;  private boolean writeAcceptCharset;  protected void writeInternal(String s, HttpOutputMessage outputMessage)      throws IOException {    if (this.writeAcceptCharset) {      outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());    }    Charset charset = getContentTypeCharset(outputMessage.getHeaders()        .getContentType());    StreamUtils.copy(s, charset, outputMessage.getBody());  }  ...}public abstract class AbstractHttpMessageConverter<T> implements    HttpMessageConverter<T> {  protected final Log logger = LogFactory.getLog(super.getClass());  private List<MediaType> supportedMediaTypes = Collections.emptyList();  ...}

The source code above can be seen that the string will be automatically encoded into the default format of ISO-8859-1, so there is a corresponding solution.

Solution 1:

@RequestMapping(value = “/test”,produces=”text/html;charset=UTF-8;”)

Solution 2:

Note that you must use spring 3.1.x or later.

<mvc:annotation-driven>  <mvc:message-converters register-defaults="true">    <bean class="org.springframework.http.converter.StringHttpMessageConverter">     <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>    </bean>   </mvc:message-converters> </mvc:annotation-driven>

Solution 3:

If @ ResponseBody is not used, change the request processing to the following:

@ RequestMapping ("/ajax") public void ajaxCharacter (HttpServletResponse response) throws IOException {PrintWriter out = response. getWriter (); out. print ("test"); out. close ();}

The above is to solve springMVC's garbled code problem. If you have any questions, please leave a message or contact the community on this site. Thank you for reading this article and hope to help you. Thank you for your support for this site!

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.