创建过滤器
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("到达过滤器");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//将拦截的请求放行,通往controller处理
filterChain.doFilter(servletRequest, servletResponse);
//controller处理完,返回时又经过了过滤器
System.out.println("返回时,又经过了过滤器");
}
}
创建监听器
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
@Component
public class Listener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
System.out.println("上下文对象创建了");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("上下文对象销毁了");
}
}
@Component
public class Listener2 implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("ServletRequest创建了");
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("ServletRequest销毁了");
}
}
@Component
public class Listener3 implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("HttpSession域对象创建了");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("HttpSession域对象销毁了");
}
}