简介

SpringBoot可以简化开发流程,但是在其中如何使用传统的J2EE servlet/listener/filter呢

@Bean配置

在Configuration类中加入filter和servlet的registration

@Bean
	public FilterRegistrationBean registFilter() {
	    FilterRegistrationBean registration = new FilterRegistrationBean();
	    registration.setFilter(new Filter(){
			@Override
			public void init(FilterConfig filterConfig) throws ServletException {
			}

			@Override
			public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
				System.out.println("in filter");
				chain.doFilter(request, response);
			}

			@Override
			public void destroy() {
			}
	    	
	    });
	    registration.addUrlPatterns("/*");
	    registration.setOrder(1);
	    return registration;
	} 
	
	@SuppressWarnings("serial")
	@Bean
	public ServletRegistrationBean registServlet() {
		ServletRegistrationBean servletRegist=new ServletRegistrationBean();
		servletRegist.setServlet(new HttpServlet (){
			@Override
		    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		            throws ServletException, IOException {
		        resp.getWriter().write("inside servlet");
		    }
		});
		servletRegist.addUrlMappings("/registedServlet");
		return servletRegist;
	} 

运行项目就可以访问servlet和filter了,在registrationBean中可以配置路径和实例。

使用Servlet3.0

如果使用Servlet3.0的话,可以在Configuration类上加@ServletComponentScan("类路径")
并开发对应的filter、listener、servlet

@WebFilter
public class CustFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("in filter2");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}

@WebListener
public class CustListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("session created");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}
}

@WebServlet(urlPatterns={"/cust"})
public class CustServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getSession().setAttribute("a", "1");
		resp.getWriter().write("cust servlet");
	}
}

在访问localhost:8080/cust时,对应的filter、listener、servlet都会被访问到