过滤器Filter(重点)
它是用来过滤网站的数据
Filter开发步骤:
-
导入包
<dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!--连接数据库--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> </dependencies>
-
编写过滤器
-
继承Filter的时候导包不要错,是javax.servlet下的
-
实现Filter接口,重写对应的方法。重点是让他继续往下走
package com.hxl.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初始化"); } //filterChain /* 1.过滤中的所有代码,在过滤待定请求的时候都会执行 2.必须要让过滤器继续同行 */ 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销毁"); } }
-
在xml中配置Filter过滤器,尽量不用全过滤,比如用户,或者管理员那个
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>ShowServlet</servlet-name> <servlet-class>com.hxl.servlet.ShowServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/servlet/s1</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.hxl.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!--只要是/servlet的任何请求,都会经过这个过滤器--> <url-pattern>/servlet/*</url-pattern> <!--<!–都会经过这个过滤器–>--> <!--<url-pattern>/*</url-pattern>--> </filter-mapping> </web-app>
-