@WebServlet(urlPatterns = "/hello") public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Hello"); } }
当我们访问过滤指定路径的时候及会经过过滤器
@WebFilter(urlPatterns = {"/css/*","/hello"}) public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info("初始化---------->完成"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { log.info("Filter---------->工作"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { log.info("销毁---------->完成"); } }
@WebListener @Slf4j public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { log.info("Listener监听到项目初始化"); } @Override public void contextDestroyed(ServletContextEvent sce) { log.info("Listener监听到项目销毁"); } }
当我们项目销毁的时候,监听器执行了。
@WebServlet(urlPatterns = “/hello”)
@WebFilter(urlPatterns = {"/css/*","/hello"})
@WebListener
依旧是我们原来的代码,只是把这三个注解注释了~这样子就是普通的java文件了
注意:proxyBeanMethods = true 表示这个配置类被代理了,false则不被代理。
简单说就是:当为true时,你无论调用几次,它永远上是同一个对象。
当为false时,每一次调用都会拿到一个新的对象。
@Configuration(proxyBeanMethods = true) public class MyRegisterConfig { @Bean public ServletRegistrationBean newServlet(){ MyServlet myServlet = new MyServlet(); return new ServletRegistrationBean(myServlet,"/hello","/ya"); } @Bean public FilterRegistrationBean newFilter(){ MyFilter myFilter = new MyFilter(); //第一种:我们前面设置了什么路径,Filter就拦截什么路径 /* return new FilterRegistrationBean(myFilter,newServlet());*/ //第二种,重新指定拦截路径,前面的就失效了。 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter); filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/ya")); return filterRegistrationBean; } @Bean public ServletListenerRegistrationBean myListener(){ MytListener mytListener =new MytListener(); return new ServletListenerRegistrationBean(mytListener); } }
如有错误,欢迎指正。