解決SpringMVC的@ResponseBody返回中文亂碼


SpringMVC的@ResponseBody返回中文亂碼的原因是SpringMVC默認處理的字符集是ISO-8859-1,在Spring的org.springframework.http.converter.StringHttpMessageConverter類中可以看到如下代碼:

public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解決返回中文亂碼的問題有兩種,第一種是局部的,只針對於某個方法的返回進行處理,第二種是全局的,針對於整個項目,如下:

第一種:在@RequestMapping中添加produces="text/html;charset=UTF-8,如:

@RequestMapping(value="/login.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")  @ResponseBody  public String login(@RequestParam(value="username") String userName,@RequestParam(value="password") String password){   return JSONMessageUtil.getSuccessJSON("登錄成功");  }

第二種:在配置文件中的mvc:annotation-driven中添加如下代碼:

<mvc:annotation-driven >   <!-- 消息轉換器 -->   <mvc:message-converters register-defaults="true">    <bean class="org.springframework.http.converter.StringHttpMessageConverter">     <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>    </bean>   </mvc:message-converters>  </mvc:annotation-driven>  <mvc:resources location="/resources/" mapping="/resources/**" />

對於亂碼問題,這樣就可以正常顯示中文了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM