11 过滤器(Filter)
什么是过滤器(Filter)
Filter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登录验证....
Filter开发步骤:
-
导包
<dependencies> <!-- servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- JSP依赖--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</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> <!-- 连接数据库--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> </dependencies>
-
编写过滤器
注意: 导包
import javax.servlet.*;
-
实现Filter接口, 重写对应的方法
package com.karl.filter; import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现! public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter初始化"); } // Chain :链 /* 1.过滤中的所有代码,在过滤特定请求的机候都会执行 2.必须要让过滤器继续通行 chain.doFilter( request,response); */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); System.out.println("doFilter! 1"); chain.doFilter(request,response);//让请求继续走,如果不写,程序到这里就被拦截停止! System.out.println("doFilter! 2"); } //销毁: web服务器关闭的时候,过滤会销毁 public void destroy() { System.out.println("CharacterEncodingFilter销毁"); } }
-
在
web.xml
中配置filter
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.karl.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>