SPRINGMVC character encoding for controller

Source: Internet
Author: User

When building a Web application using the SPRINGMVC framework, the client often requests data in the form of strings, integers, JSON, and so on, usually using @responsebody annotations to enable the controller to respond to the corresponding data instead of rendering a page. If the request is a non-English format string, it is often garbled in the client display. The reason is that spring's stringhttpmessageconverter default character type is iso8895-1 ' Western European language ', does not support Chinese and other characters, the concrete framework internal process is not introduced.

Here are a few solutions to summarize:

1. Use Httpserveletresponse to set the ContentType property without using @responsebody annotations

  @RequestMapping (value = "/rest/create/document")    publicvoid  Create (document Document, Httpservletrespone respone) {        repoonse.setcontenttype ("text/plain;charset= ' Utf-8 '");        Response.Write ("Chinese string");    }

2. Return Response Entity object, set contenttype, for example:

  @RequestMapping (value = "/rest/create/document")    public responseentity<string>  Create (document document, Httpservletrespone respone) {        new  httpheaders ();        Responseheaders.add ("Content-type", "text/html; Charset=utf-8 ");         = documentservice.create (Document);         = jsonserializer.serialize (newdocument);         return New Responseentity<string>(JSON, responseheaders, Httpstatus.ok);    }

3. Use the produces property:

@RequestMapping (value = "/rest/create/document", produces= "Text/plain;charset=utf-8")    @ResponseBody     publicthrows  unsupportedencodingexception {        = documentservice.create ( Document);         return jsonserializer.serialize (newdocument);    }

SPRINGMVC character encoding for controller

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.