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