一、过滤器:在servlet之前的一个门槛,负责拦截请求和响应;
二、创建过滤器:
1.实现Filter接口;//tomcat9.0以前实现3个方法,以后只需实现doFilter方法;
2.继承HttpFilter类;//实现doFilter方法;
三、Filter接口:
核心方法:
(1)init(FileterConfig):Filter实例后,马上调用init()初始化,且只执行一次;
(2)destory():服务器被合法关闭的时候执行;
(3)doFilter(HttpServletRequest req,HttpServletResponse res,FilterChain chain):
每次访问的时候都执行一次;
//参数:FilterChain:过滤器链对象
四、FilterChain接口:
请求放行:doFilter(ServletRequest,ServletResponse);
五、配置过滤器:
1.基于注解配置:
@WebFilter("url-parrent")
url-parrent:要过滤的资源的路径
@WebFilter("/*") public class FilterTest extends HttpFilter { @Override protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("filter........"); chain.doFilter(request, response); } }v
2.基于web.xml配置:
<filter> <filter-name></filter-name> <filter-class></filter-class> </filter> <filter-mapping> <filter-name></filter-name> <!-- 要过滤的资源的路径 --> <url-parrent></url-parrent> </filter-mapping>
3.url-parrent参数:
//支持层级:/xxx/xxx.jsp;
1)精准:/xxx.jsp;/xxx;
2)模糊:
*.jsp:所有jsp;
*.do:所有servlet;
3)所有:/*;
原文地址:https://www.cnblogs.com/Tractors/p/11279678.html
时间: 2024-10-16 03:54:02