SpringMVC配置自定义过滤器
环境
- 开发工具: idea2019.3.5
- springmvc版本: 5.1.9.RELEASE
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
第一种方式: 手写过滤器进行配置 注意Filter接口是servlet里面的
- 书写过滤器类
关于乱码过滤器类, 可以在百度更详细的大神写的乱码过滤器,该处只是简易教授配置过滤器的demo
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
/**
* 手写简易编码过滤器,用于解决post请求的中文编码乱码问题
* @author suncp
* @date 2020/11/29 23:21
*/
@Component
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {}
}
- 将手写的过滤器配置到web.xml中
<!--自定义过滤器解决乱码问题-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.suncp.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<!--/* 可以把jsp页面也加载进去,否则只能过滤请求-->
<url-pattern>/*</url-pattern>
</filter-mapping>
第二种方式: 使用springMVC自带的过滤器类
- 直接配置到web.xml中, 类已经存在mvc包中(CharacterEncodingFilter)
- 关于CharacterEncodingFilter, 实际上继承多个抽象类, 根本上是实现了Filter接口
<!--配置SpringMVC的乱码过滤 - 使用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>
继承关系: