标签:code ebs desc static @class ret listener tco return
SpringBoot中有两种方式可以添加 Servlet、Filter、Listener。
1.代码注册,通过ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 获得控制
1) Servlet
@Bean public ServletRegistrationBean servletRegistrationBean() { return new ServletRegistrationBean(new MyServlet(), "/xs/*"); }
2.在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet(urlPatterns = "/test/*")、@WebFilter、@WebListener 注解自动注册,这些注解都是JDK的,无需其他代码。
1) Servlet
@SpringBootApplication @ServletComponentScan(basePackages={"com.xsjt"}) public class SpringBootSampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSampleApplication.class, args); } }
2) Filter
/** * @Description 自定义的Serlvlet过滤器 * @ClassName MyFilter * @Date 2017年11月1日 下午2:29:50 */ @WebFilter(filterName = "myFilter", urlPatterns = "/*") public class MyFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; System.out.println(req.getRequestURL() + "------>doFilter"); chain.doFilter(request, response); } public void destroy() { // TODO Auto-generated method stub } }
3) Listener
/** * @Description 自定义监听器 * @ClassName MyListener * @Date 2017年11月1日 下午2:31:18 */ @WebListener public class MyListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext 初始化"); System.out.println(sce.getServletContext().getServerInfo()); } public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext 销毁"); } }
SpringBoot(四)-- 整合Servlet、Filter、Listener
标签:code ebs desc static @class ret listener tco return
原文地址:http://www.cnblogs.com/xbq8080/p/7768916.html