首页 > 解决方案 > spring WebApplicationInitializer 配置多个servlet

问题描述

我需要配置 2 个 servlet:一个用于常规 http 请求,另一个是用于 Java web-socket 的 Atmosphere servlet。

这是我的 WebApplicationInitializer 的代码:

public class AppInitializer implements WebApplicationInitializer
{
    private static final String CONFIG_LOCATION = "com.mysite.myapp.presentation.config";
    private static final String MAPPING_URL = "/*";
    private static final String STREAM_URL = "/stream/*";

    private int servletInx = 1;
    private ServletContext servletContext;

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException
    {
        this.servletContext = servletContext;
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        registerServlet("DispatcherServlet", new DispatcherServlet(context), MAPPING_URL);
        registerServlet("AtmosphereServlet", new AtmosphereServlet(), STREAM_URL);
    }

    private AnnotationConfigWebApplicationContext getContext()
    {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        return context;
    }

    private void registerServlet(String servletName, Servlet servletClass, String mappingUrl)
    {
        ServletRegistration.Dynamic dispatcher =
            servletContext.addServlet(servletName, servletClass);

        if (dispatcher != null)
        {
            System.out.println("servletInx: " + servletInx);
            dispatcher.setLoadOnStartup(servletInx++);
            dispatcher.addMapping(mappingUrl);
        }
    }
}

运行应用程序时,http 部分工作正常;但是,没有提供静态文件。甚至 webapps/myapp (localhost:8080/myapp/index.html) 的 index.html 也返回 404

当控制器通过 /@RequestMapping(value = "/welcome", method = RequestMethod.GET) 返回相同的 html 时,它可以工作,但 html 中指定的任何 javascript 或 css 都会返回 404

任何帮助将不胜感激

标签: javaspringconfiguration

解决方案


抱歉,它与 WebApplicationInitializer 无关。它与 WebMvcConfigurerAdapter 有关。它缺少启用配置器的 configureDefaultServletHandling 方法。这反过来又使应用程序能够提供静态内容。

很抱歉挠头;-)


推荐阅读