前言? ? ? ??
????????本文介紹了springMVC中文亂碼的解決方案,同時也貼出了本人遇到過的其他亂碼情況,可以根據自身情況選擇合適的解決方案。
其他-jdbc、前端、后端、jsp亂碼的解決
Tomcat導致的亂碼解決
自定義中文亂碼過濾器
老方法,通過javaWeb-Filter解決
準備工作
1.把上一章中的取消數據綁定的設置注釋掉:
//恢復注解@NotEmpty(message="不能為空")private String name;
//MonsterHandler中注釋掉取消數據綁定
//webDataBinder.setDisallowedFields("name");
2.輸入中文:
3.后臺顯示中文亂碼:name='??????'
Filter回顧
Filter的生命周期圖解
自定義實例
1.創建com/stein/springMVC/filter/MyCharacterFilter.java
import javax.servlet.*;
//注意Filter接口不要引用錯了
public class MyCharacterFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {}@Overridepublic void destroy() {}
}
2.在doFilter()中執行
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {//設置utf-8編碼servletRequest.setCharacterEncoding("utf-8");//放行過濾器filterChain.doFilter(servletRequest,servletResponse);}
3.在web.xml中配置Filter
????????建議放在最前面
<!--配置自定義的中文亂碼過濾器--><filter><filter-name>MyCharacterFilter</filter-name><filter-class>com.stein.springMVC.filter.MyCharacterFilter</filter-class></filter><filter-mapping><filter-name>MyCharacterFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
4.重新測試
? ? ? ? 后臺輸出:name='佩恩'。亂碼解決
Spring提供的過濾器?
? ? ? ? 通過上面的自定義的方法,在代碼中寫死了字符集是"uft-8",屬于硬編碼的方式,不夠靈活;自己靈活處理的話,又比較麻煩。于是有了spring給我們提供的字符過濾器。
1.在web.xmlx中注釋掉剛剛自己定義的MyCharacterFilter
2.重新配置spring的過濾器
? ? ? ? 1)utf-8 或者 UTF-8都一樣
? ? ? ? 2)encoding這個參數名,可以在CharacterEncodingFilter這個類名,按Ctrl+B進入查看到
<!--使用spring提供的過濾器處理中文,放在其它Servlet前--><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><!--大小寫都可以 utf-8--><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
3.重新測試
? ? ? ? 中文正常顯示!