ajax发送请求,其中请求带有中文参数,后台spring接收到参数是乱码的,可使用spring提供的过滤器解决:
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
其中,/rest/* 为spring的统一路径前缀,即过滤所有url前缀为的/rest/的请求,spring接收中文参数使用utf-8编码;
注意:forceEncoding的值一定要设为true,spring才会使用过滤器配置的编码值(这个例子是utf-8)来编码请求参数。
CharacterEncodingFilter其中一段代码:
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);
}
}
filterChain.doFilter(request, response);
}
这个方法在服务器是window、linux系统环境下都可以使用。