3

【笔记】Filter快速入门

 1 year ago
source link: https://feiju12138.github.io/2022/10/02/Filter%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Filter快速入门

  • 创建Web项目,引入Servlet依赖

pom.xml

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

创建过滤器类

  • 创建一个类,实现javax.servlet.Filter接口
  • 使用@WebFilter定义过滤的请求,当接收到过滤请求时,会自动执行doFilter()方法
  • 使用chain.doFilter(request, response)放行请求
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(servletRequest, servletResponse);
}

public void destroy() {

}
}

哔哩哔哩——黑马程序员


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK