#创作挑战赛#

10.2 Filter快速入门10.2.1 开发步骤

进行 Filter 开发分成以下三个步骤实现:

package web.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * @Author 晨默 * @Date 2022/9/11 10:47 */ // 步骤2: @WebFilter("/*") public class FilterDemo1 implements Filter { // 步骤1 @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 步骤3 System.out.println("FilterDemo1...."); // 这语句代表对资源进行放行,允许访问本该访问的资源 filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }

10.2.2 代码演示

pom.xml 具体如下所示:

<?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>FilterDemo</name> <groupId>org.example</groupId> <artifactId>FilterDemo</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> <java.version>16</java.version> <maven.compiler.source>16</maven.compiler.source> <maven.compiler.target>16</maven.compiler.target> </properties> <build> <plugins> <!-- Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 访问端口号 --> <port>5050</port> <path>/</path> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> </project>

报错警示:会出现 Java 不支持 Java5 版本

此时需要在 项目结构 中的模块中设置编译语言,与使用的语言版本一直即可,

java里面的filter是干啥用的(JavaWeb20-2Filter快速入门)(1)

java里面的filter是干啥用的(JavaWeb20-2Filter快速入门)(2)

<%-- Created by IntelliJ IDEA. User: 晨默 Date: 2022/9/11 Time: 11:05 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>Hello Filter!</h1> </body> </html>

演示效果
  1. 当 过滤器的 dofilter() 中没有编写 filterChain.doFilter(servletRequest,servletResponse); 语句时,访问 hello.jsp 页面 没有任何效果,在 idea 控制台 会打印如下内容:

java里面的filter是干啥用的(JavaWeb20-2Filter快速入门)(3)

  1. 编写了 filterChain.doFilter(servletRequest,servletResponse); 后,hello.jsp 页面就可以正常显示了

,