servlet3.0 新特性和springboot Listener和filter案例
1.filter
package com.newtouch.zxf.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Order(1) @WebFilter(filterName="LoginFilter",urlPatterns="/*") @Component public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("TestFilter1"); chain.doFilter(request,response); } @Override public void destroy() { // TODO Auto-generated method stub } }
1、@Component 这个注解的目的是将LoginFilter交给容器来处理。也就是让LoginFilter起作用
2、@order确定多个filter的执行顺序 数字越小越先执行
package com.newtouch.zxf.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import org.springframework.stereotype.Component; @WebListener @Component public class MyListerner implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.print("--------------contextDestroyed"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.print("--------------contextDestroyed"); } }
1.@WebListener 标记这个类是一个监听器 2.@Component 这个注解的目的是将LoginFilter交给容器来处理。也就是让LoginFilter起作用