Spring JavaConfig: Add mapping for custom Servlet

走远了吗. 提交于 2020-01-11 02:13:45

问题


In a javaconfig-based Spring 4.0 project, how can I add a mapping for a certain URL to a Servlet other than the Spring DispatcherServlet.

Im my case I want to use h2console from H2 database which is provided through the servlet org.h2.server.web.WebServlet

Edit: In the upcoming Spring Boot 1.3 the h2console can be enabled with a configuration parameter: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-sql-h2-console

Enabling it is as simple as adding these two lines to your application.properties:

spring.h2.console.enabled=true
spring.h2.console.path=/console

回答1:


The easiest way is to use initializer implementing directly WebApplicationInitializer and the add into onStartup(ServletContext servletContext) method following code;

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


来源:https://stackoverflow.com/questions/21244066/spring-javaconfig-add-mapping-for-custom-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!