java - 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
任何帮助将不胜感激
解决方案
抱歉,它与 WebApplicationInitializer 无关。它与 WebMvcConfigurerAdapter 有关。它缺少启用配置器的 configureDefaultServletHandling 方法。这反过来又使应用程序能够提供静态内容。
很抱歉挠头;-)
推荐阅读
- node.js - 使用 facebook-node-sdk nodejs 从 facebook api 检索用户数据?
- c++ - 如何让 clang 格式在 << 和 >> 上中断
- javascript - 如何从javascript执行cgi脚本
- javascript - 如何修复 Puppeteer 中的“没有这样的文件或目录”错误
- tomcat - 无法访问tomcat
- java - 春季如何打造一池豆豆?
- android - 如果在 exoplayer android 中屏幕关闭,我想播放视频,如何?
- python-3.x - 通过 .trace() 调用函数时收到“NoneType Object is not Callable”错误
- python - 如何根据数据集中的条件将值从字典复制到列表中?
- swagger - 如何将对象列表和不同对象作为 API 的响应