1. 程式人生 > >@ResponseBody跨系統請求中文亂碼解決方案

@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");
	}
}