Filter:过滤器,用来过滤网站的数据
如:处理中文乱码、登录验证
1、导包
<dependencies> <!--servlet的依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--JSP的依赖--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!--JSTL表达式的依赖--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!--standard标签库--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies>
2、编写过滤器
2.1导包不要导错(选箭头指的那个)
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter { //初始化:web服务器启动,就是初试化了,随时等待过滤对象出现 public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter初试化"); } //Chain:链 //过滤器中的所有代码,在过滤器特定请求的时候会执行 //必须让过滤器继续同行 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterEncodingFilter执行前...."); filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写,程序到这里就被拦截停止了 System.out.println("CharacterEncodingFilter执行后...."); } //销毁:web服务器关闭的时候,过滤会销毁 public void destroy() { System.out.println("CharacterEncodingFilter销毁"); } }
3、在web.xml中配置Filter
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!--只要是/servlet的任何请求,会经过这个过滤器--> <url-pattern>/servlet/*</url-pattern> </filter-mapping>