Spring WebApplicationInitializer配置多个servlet

时间:2019-01-09 02:17:45

标签: java spring configuration

我需要配置2个servlet:一个用于常规的http请求,另一个是用于Java网络套接字的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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

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

很抱歉刮伤头部;-)

相关问题