spring requestMapping charset

本文介绍了解决SpringMVC框架中客户端请求中文字符串时出现乱码的问题。提供了三种解决方案:通过设置HttpServletResponse的ContentType属性、使用ResponseEntity对象设置ContentType、在RequestMapping中使用produces属性。

 

        在使用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);
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值