一、介绍
- 服务器收到请求后,将请求交给DispatcherServlet处理,这时DispatcherServlet会获取请求参数并进行封装,然后再根据请求条件找到对应的方法来处理请求。由于在进入方法前,请求参数已经被DispatcherServlet读取,所以在方法中设置编码字符集会失效。我们可以用过滤器解决中文乱码问题,SpringMVC已经实现了编码字符集的过滤器,我们只需在web.xml中配置好即可使用。
- 过滤器源码分析
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String encoding = this.getEncoding();
if (encoding != null) {
//下面的if的this.isForceRequestEncoding()在默认情况下为false,request.getCharacterEncoding()默认情况下为true,因为Request对象没有设置编码字符集
if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
}
//是否设置Response对象返回给浏览器的数据的编码字符集
if (this.isForceResponseEncoding()) {
response.setCharacterEncoding(encoding);
}
}
filterChain.doFilter(request, response);
}
- 项目测试
(1)配置过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置过滤器-->
<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>
<!--设置Response对象返回给浏览器的数据采用的编码字符集为UTF-8-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
(2)控制器
@Controller
public class MyController {
@RequestMapping(value = {"/index"})
public String index(String username, HttpServletRequest request, HttpServletResponse response){
String requestCharacterEncoding = request.getCharacterEncoding();
System.out.println(requestCharacterEncoding);
String responseCharacterEncoding = response.getCharacterEncoding();
System.out.println(responseCharacterEncoding);
System.out.println(username);
return "index";
}
}
(3)运行