springboot-web开发注册servlet三大组件

servlet三大组件分别是servlet、Filter、Listener,分别需要注册ServletRegistrationBean,FilterRegistrationBean,ServletListenerRegistrationBean,传统的web项目,这些组件的注册是在web.xml,springboot中Java代码注册组件,在web.xml可以修改的属性在这些bean组件中通通可以设置,继承HttpServlet、实现Filter、实现ServletContextListener

servlet用来处理浏览器发送的请求,接收请求数据、处理请求和完成响应,注册servlet组件需要注册ServletRegistrationBean,下面是代码示例

public class MyServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().write("hello myservlet");
	}
}
    @Bean
	public ServletRegistrationBean myServlet() {
        new ServletRegistrationBean 可以用它的有参构造器,传入自己的servlet并且写上对什么请求路径进行处理
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/hello");
		return servletRegistrationBean;
	}

Filter的作用是拦截请求和方行,想要注册Filter就是注册FilterRegistrationBean,以下是代码示例

public class MyFilter implements Filter{
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("执行了我的过滤器");
		//放行
		arg2.doFilter(arg0, arg1);
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}

    @Bean
	public FilterRegistrationBean myFilter() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
        设置过滤的请求
		filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello"));
		return filterRegistrationBean;
	}

Listener是监听器,注册监听组件需要注册ServletListenerRegistrationBean,以下是代码示例

public class MyListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("servlet容器启动了");
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("servlet容器销毁了");
	}
}
    @Bean
	public ServletListenerRegistrationBean myListener() {
		ServletListenerRegistrationBean listenerRegistrationBean = new ServletListenerRegistrationBean(new MyListener());
		return listenerRegistrationBean;
	}

 

你可能感兴趣的:(SpringBoot)