Springboot中Web原生组件的注入

一、使用原生的Servlet

注意:要在springboot中能够扫描到web组件 需要使用注解,在主程序application类中加上
@ServletComponentScan(basePackages = “com.zhm.component”) :指定原生Servlet组件都放在那里

//servlet组件
@WebServlet(urlPatterns = {"/myServlet"})
public class MyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Hello World!");
    }
}
//Filter组件
@WebFilter(urlPatterns = "/myservlet")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}
//listener组件
@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监听到项目销毁");
    }
}

二、使用RegistrationBean将servlet注入

/**
* 使用这种方式可以直接将写好的servlet代码注入到容器中
* ServletRegistrationBean  对应servlet
* FilterRegistrationBean  对应filter
* ServletListenerRegistrationBean  对应listen
*/
@Configuration
public class FilterConfig {

    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet());
        servletRegistrationBean.setUrlMappings(Arrays.asList("/myServlet"));
        return servletRegistrationBean;
    }
    
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new LoginFilter());
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/myservlet"));
        return filterRegistrationBean;
    }
    
	@Beans
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        MytListener mytListener =new MytListener();
        return  new ServletListenerRegistrationBean(mytListener);
    }


}

你可能感兴趣的:(SpringBoot学习,spring,boot,java)