如何把web.xml中的context-param、Servlet、Listener和Filter定义添加到SpringBoot中

时间:2021-02-22 13:22:58

把传统的web项目迁移到SpringBoot中,少不了web.xml中的context-param、Servlet、Filter和Listener等定义的迁移。 对于Servlet、Filter和Listener相关定义转换相对来说比较明确:

Servlet定义的迁移

一般servlet的迁移

@WebServlet("/jsonIndexSearchServlet")
public class JsonIndexSearchServlet extends HttpServlet {
    ...
}

FacesServlet的迁移

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        FacesServlet servlet = new FacesServlet();
        //, "*.jsf"
        ServletRegistrationBean bean = new ServletRegistrationBean(servlet);
        bean.setOrder(40);
        bean.setName("FacesServlet");
        List<String> urlPattern = new ArrayList<>();
        urlPattern.add("*.jsf");
        bean.setUrlMappings(urlPattern);
        return bean;
    }

Listener定义的迁移

    @Bean
    public ServletListenerRegistrationBean<ServletContextListener> setStartupServletContextListener(){
        ServletListenerRegistrationBean<ServletContextListener> result = new ServletListenerRegistrationBean<>();
        result.setListener(new StartupServletContextListener());
        result.setOrder(20);
        return result;
    }

Filter定义的迁移

    @Bean
    public FilterRegistrationBean rewriteFilter() {
        FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
        rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
                DispatcherType.ASYNC, DispatcherType.ERROR));
        rwFilter.addUrlPatterns("/*");
        rwFilter.setOrder(30);
        return rwFilter;
    }

context-param定义的迁移

    @Bean
    public InitParameterConfiguringServletContextInitializer initParamsInitializer() {
        Map<String, String> contextParams = new HashMap<>();
        contextParams.put("org.apache.myfaces.AUTO_SCROLL", "true");
        return new InitParameterConfiguringServletContextInitializer(contextParams);
    }