@WebServlet(urlPatterns = "/myServlet/*")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("********get请求***********");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
System.out.println("********post请求***********");
}
}
在启动类上添加注解@ServletComponentScan,过滤器和监听器也需要开启该注解。
@WebFilter(urlPatterns="/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.err.println("********过滤器初始化*********");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.err.println("********过滤器执行*********");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.err.println("********过滤器销毁*********");
}
}
@WebListener
public class MyServletContextListen implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.err.println("***********容器启动**************");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.err.println("***********容器销毁**************");
}
}
其中示例中的监听器为监听容器的启动及销毁,还存在其他的监听器接口,例如监听session的HttpSessionListener(多用于统计在线人数),监听ServletRequest对象的ServletRequestListener
自定义拦截器:
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.err.println("*********拦截器1执行*********");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
public class MyInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.err.println("***********拦截器2执行**************");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
将自定义拦截器加入到拦截器链:
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor1());
registry.addInterceptor(new MyInterceptor2());
super.addInterceptors(registry);
}
}
这里过滤器,监听器,拦截器有个请求顺序,例如对于同一个请求,会先执行监听该请求的监听器,然后执行过滤器,再执行拦截器。