【问题标题】:spring WebApplicationInitializer configure multiple servletsspring WebApplicationInitializer 配置多个servlet
【发布时间】:2019-06-03 18:32:30
【问题描述】:

我需要配置 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

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

任何帮助将不胜感激

【问题讨论】:

    标签: java spring configuration


    【解决方案1】:

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

    对不起,挠头了;-)

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2014-03-05
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      相关资源
      最近更新 更多