如何解决SpringMVC接收到的请求参数为乱码的问题
Get请求
直接设置tomcat目录下conf/server.xml文件,添加编码为utf-8
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
Post请求
原理
请求参数为乱码主要是因为编码的问题。需要在web配置文件中配置一个过滤器用来过滤请求,对请求进行编码。
假定最初设置的<span id="servlet">servlet</span>为:
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
需要配置一个<span id="filter">过滤器</span>:
<!-- 配置编码过滤器 characterEncodingFilter 解决中文Post乱码问题 -->
<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-name:配置一个过滤器名称后续用来配置filter-mapping
- filter-class:配置过滤器的类
- init-param:用来初始化过滤器类中的变量
- encoding:编码,将过滤器中的encoding变量设置为utf-8
- forceEncoding:是否强制转换。这个原理在这里
然后是配置过滤器需要过滤哪些请求
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
说明:
<span id="forceEncoding">forceEncoding</span>
在CharacterEncodingFilter中有一个setForceEncoding方法(org.springframework.web.filter.CharacterEncodingFilter#setForceEncoding),他会对变量forceRequestEncoding和forceResponseEncoding进行赋值,代码如下:
public void setForceEncoding(boolean forceEncoding) {
this.forceRequestEncoding = forceEncoding;
this.forceResponseEncoding = forceEncoding;
}
而在过滤的方法doFilterInternal方法(org.springframework.web.filter.CharacterEncodingFilter#doFilterInternal)中会通过forceRequestEncoding和forceResponseEncoding的值来判断是否需要对请求和响应进行编码:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String encoding = this.getEncoding();
if (encoding != null) {
if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
}
if (this.isForceResponseEncoding()) {
response.setCharacterEncoding(encoding);
}
}
filterChain.doFilter(request, response);
}
网友评论