在使用springMVC框架构建web应用,客户端常会请求字符串、整型、json等格式的数据,通常使用@ResponseBody注解使 controller回应相应的数据而不是去渲染某个页面。如果请求的是非英文格式的字符串,往往在客户端显示的是乱码。原因是spring的 StringHttpMessageConverter默认的字符类型是iso8895-1 ‘西欧语言’,不支持中文等字符,具体的框架内部流程不作介绍。
这里总结几种解决方案:
1.不使用@ResponseBody注解,使用HttpServeletResponse设置contentType属性
@RequestMapping(value ="/rest/create/document") public void create(Document document, HttpServletRespone respone) { repoonse.setContentType("text/plain;charset='utf-8'"); response.write("中文string"); }
2.返回Response Entity object,设置contentType,例:
@RequestMapping(value = "/rest/create/document") public ResponseEntity<String> create(Document document, HttpServletRespone respone) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "text/html; charset=utf-8"); Document newDocument = DocumentService.create(Document); String json = jsonSerializer.serialize(newDocument); return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK); }
3.使用produces属性:
@RequestMapping(value = "/rest/create/document",produces= "text/plain;charset=UTF-8") @ResponseBody public String create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException { Document newDocument = DocumentService.create(Document); return jsonSerializer.serialize(newDocument); }