使用过滤器解决乱码问题
方法一:自己编写过滤器
过滤器 在自己的包下创建一个过滤器
package com.miao.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
public void destroy() {
}
}
配置web.xml filter-class的位置配置自己写的过滤器的位置
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.miao.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
方法二:使用springmvc自带过滤器
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 注意,url-pattern的位置一定要写 / * 不然会无法过滤jsp页面导致乱码
如果以上两个方法都没有解决乱码问题,就去查看tomcat的配置是否有问题
apache-tomcat-8.0.46->conf->server.xml
在Connertor的末尾加上 URIEncoding="UTF-8"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
|