有人跟蹤@ResponseBody
下面提供2中解決方法:
我遇到這個問題的時候,查閱了一下資料,采用了一個比較簡單的方法來解決這個問題,就是需要服務(wù)器返回中文的時候不使用這個注解,而是直接用HttpServletResponse的對象來完成傳輸,在服務(wù)器端可以通過response.setContentType("text/plain;charset=UTF-8");來設(shè)定編碼類型,這樣就不會出現(xiàn)中文亂碼了。
服務(wù)器端核心代碼如下:
[java] view plain copy print?@RequestMapping(value = "test", method = RequestMethod.POST) public void test(HttpServletRequest request, HttpServletResponse response) { String result = null; //取得客戶端傳來的值 String userName = request.getParameter("userName"); //向客戶端返回一句話 result = "您好!"; PrintWriter out = null; response.setContentType("text/plain;charset=UTF-8"); try { out = response.getWriter(); out.write(result.toString()); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } } 返回值時根據(jù)自己的數(shù)據(jù)類型進行設(shè)置,常用的有:response.setContentType("text/html; charset=utf-8"); htmlresponse.setContentType("text/plain; charset=utf-8"); 文本response.setContentType("application/json; charset=utf-8"); 數(shù)據(jù)response.setContentType("application/xml; charset=utf-8");
2014-07-11
今天再次查找了一下這個問題,有了一個更好的解決方法,使用spring的BeanPostProcessor接口實現(xiàn),在自己的工程中新建一個類,如下:
[java] view plain copy print?package springmvc.extention; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.http.MediaType; import org.springframework.http.converter.StringHttpMessageConverter; /** * 解決spring MVC3 中@ResponseBody的中文亂碼問題 */ public class UTF8StringBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof StringHttpMessageConverter) { MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8")); List<MediaType> types = new ArrayList<MediaType>(); types.add(mediaType); ((StringHttpMessageConverter) bean).setSupportedMediaTypes(types); } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } } 然后在自己的Spring配置文件中注冊這個bean就可以了,再試試自己的程序,發(fā)現(xiàn)問題解決了。[html] view plain copy print?<!-- 解決使用@ResponseBody 的中文亂碼。 --> <bean class="springmvc.extention.UTF8StringBeanPostProcessor"></bean>(原文地址:http://blog.csdn.NET/zhshulin)
新聞熱點
疑難解答