SpringMVC接收请求参数时的中文乱码问题
在web.xml中注册字符编码过滤器(其中有两个参数需要设置encoding和forceEncoding)
在过滤器底层代码中有一个方法doFilterInternal()其中if语句的判断中只要将forceEncoding设置为true(默认的是false),才能够保证中文乱码问题的解决,只需要在web.xml中设置编码就好,其它地方一律不需要;
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>