javaweb学习----5.Filter&Listener
程序员文章站
2022-04-29 10:42:10
FilterFilter过滤器是JavaWeb三大组件之一(Filter,Listener,Servlet),JavaEE的规范作用:拦截请求,过滤响应。常见应用场景:权限检查,日记操作,事务管理…初体验:@WebFilter(filterName = "Filter1",urlPatterns = {"/img/*"})public class Filter1 implements Filter{@Overridepublic void doFilter(ServletRequest...
Filter
Filter过滤器是JavaWeb三大组件之一(Filter,Listener,Servlet),JavaEE的规范
作用:拦截请求,过滤响应。
常见应用场景:权限检查,日记操作,事务管理…
初体验:
@WebFilter(filterName = "Filter1",urlPatterns = {"/img/*"})
public class Filter1 implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
System.out.println("经过了过滤器...");
if(session.getAttribute("user") != null) {
chain.doFilter(request, response);
}else {
request.getRequestDispatcher("/index.jsp").forward(request, response);
return ;
}
}
}
Filter的生命周期
构造方法—>init()方法—>doFilter()方法—>destory()方法
FilterConfig
Filter过滤器的配置类,可以获取Filter的name,init-param,获取ServletContext对象.
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init....");
String filterName = filterConfig.getFilterName();
String param = filterConfig.getInitParameter("param");
ServletContext servletContext = filterConfig.getServletContext();
}
当多个过滤器执行时,他们执行的优先顺序是按照他们在web.xml中从上到下配置的顺序决定.
所有filter默认是在同一个线程中执行的
Listener
web的三大组件之一
事件监听机制:
- 事件:一件事情
- 事件源:事件发生的地方
- 监听器:一个对象
- 注册监听:将事件、事件源、监听器绑定在一起,当事件源上发生某个事件后,执行监听器代码
ServletContextListener:监听ServletContext对象的创建和销毁
default public void contextInitialized(ServletContextEvent sce) {}
default public void contextDestroyed(ServletContextEvent sce) {}
自定义Listener:
@WebListener(value = "一个Listener")
public class Listener1 implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
String parameter = servletContext.getInitParameter("param");
System.out.println("contextInitialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed");
}
}
本文地址:https://blog.csdn.net/weixin_44246189/article/details/107281119