* 手写过滤器,然后在web.xml文件中配置该过滤器。
- 过滤器:
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
- 在XML文件中配置
<!--自己的过滤器-->
<filter>
<filter-name>myencoding</filter-name>
<filter-class>com.shi.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myencoding</filter-name>
<url-pattern>/*</url-pattern> // /*过滤所有文件 /过滤所有文件 但是不包括jsp
</filter-mapping>
第二种方式 在web.xml文件中配置SpringMVC 提供的过滤器
<!--SpringMVC提供的过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
原文:https://www.cnblogs.com/szqengr/p/14770828.html