今天撰寫網頁時遇到了JSP亂碼問題,在conroller回傳到view之前是沒有編碼的問題的,但到了view後顯示的卻是問號亂碼如下圖
首先當然先確認前端是否有設定UTF-8
我後端原本就有寫了filter,但還是無法,在網路上找了spring的做法,在web.xml加上以下
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但問題仍然沒解決,因為在此設置只會解決request的encoding 即使使用ForceEncoding也無法解決這個case
再google了一下,發現原因
Later found that because the return json in the controller used @ResponseBody, and spring source @ ResponseBody the realization of the class found its default encoding is iso-8859-1, and the project with the encoding for the utf-8, so the Chinese will appear Garbled.
主要是說spring annotation預設編碼為 iso-8859-1 雖然專案設定utf-8 仍然會造成混淆
於是大部分推薦的最終解決方法是加上
@RequestMapping(value="/initValues",method = {RequestMethod.POST} , produces="text/plain")
這樣就沒問題啦~~