@ResponseBody跨系统请求中文乱码解决方案

一.原因

spring mvc的一个bug,spring MVC有一系列HttpMessageConverter去处理用@ResponseBody注解的返回值,如返回list则使用MappingJacksonHttpMessageConverter,返回string,则使用StringHttpMessageConverter,这个convert使用的是字符集是iso-8859-1,而且是final的

二.可以自己定义返回方法

案例代码:

@Controller
@RequestMapping("/dorm/mobile/enterpriseWeChat")
public class EnterpriseWeChatController extends BaseController{
	@Resource
	public EnterpriseWeChatService enterpriseWeChatService;
	@Resource
	public DormAreaService dormAreaService;
	@RequestMapping("/getInitialData")
	public void getInitialData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		Map<String, Object> map = new HashMap<String,Object>();
		
		
		List<Area> areaList=enterpriseWeChatService.findByJpql("FROM Area WHERE areaId IN ("+dormAreaService.getAreaIdStrByEmpNo("CH4757")+") AND isEnabled=0");
		
		map.put("areaList",areaList);
		msgReturnForMobile(response, map);
	}

	public static void writeResultForMobile(HttpServletResponse response, String writeContent, String contentType) {
		if (contentType == null) {
			response.setContentType("text/html");
		} else {
			response.setContentType(contentType);
		}
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(URLEncoder.encode(writeContent, "UTF-8"));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void msgReturnForMobile(HttpServletResponse response, Map<String, Object> mp){
		JSONObject jo = JSONObject.fromMap(mp);
		writeResultForMobile(response, jo.toString(), "text/html;charset=UTF-8");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值