Spring JavaConfig:为自定义Servlet添加映射

ygl*_*odt 7 java spring h2 spring-boot

在基于javaconfig的Spring 4.0项目中,如何将某个URL的映射添加到除Spring DispatcherServlet之外的Servlet.

我的情况我想使用H2数据库中的h2console,这是通过servlet提供的 org.h2.server.web.WebServlet

编辑:在即将到来的Spring Boot 1.3中,可以使用配置参数启用h2console:http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-sql-h2 -安慰

启用它就像将这两行添加到您的application.properties:

spring.h2.console.enabled=true
spring.h2.console.path=/console
Run Code Online (Sandbox Code Playgroud)

Jak*_*ski 10

最简单的方法是使用初始化程序直接实现WebApplicationInitializer和onStartup(ServletContext servletContext)代码之后的add into 方法;

ServletRegistration.Dynamic h2Servlet = servletContext.addServlet("h2Servlet", new org.h2.server.web.WebServlet());
h2Servlet.setLoadOnStartup(1);
h2Servlet.addMapping("/h2/*");
Run Code Online (Sandbox Code Playgroud)