【发布时间】:2016-06-30 05:29:36
【问题描述】:
有没有办法通过属性“上下文路径”为同一个 Spring Boot MVC 应用程序设置许多映射?我的目标是避免为 uri 映射创建许多“Dispatcherservlet”。
例如:
servlet.context-path =/, /context1, context2
【问题讨论】:
标签: spring spring-mvc spring-boot
有没有办法通过属性“上下文路径”为同一个 Spring Boot MVC 应用程序设置许多映射?我的目标是避免为 uri 映射创建许多“Dispatcherservlet”。
例如:
servlet.context-path =/, /context1, context2
【问题讨论】:
标签: spring spring-mvc spring-boot
您可以创建返回 ServletRegistrationBean 的 @Bean 注释方法,并在那里添加多个映射。这是更可取的方式,因为 Spring Boot 鼓励 Java 配置而不是配置文件:
@Bean
public ServletRegistrationBean myServletRegistration()
{
String urlMapping1 = "/mySuperApp/service1/*";
String urlMapping2 = "/mySuperApp/service2/*";
ServletRegistrationBean registration = new ServletRegistrationBean(new MyBeautifulServlet(), urlMapping1, urlMapping2);
//registration.set... other properties may be here
return registration;
}
在应用程序启动时,您将能够在日志中看到:
INFO | localhost | org.springframework.boot.web.servlet.ServletRegistrationBean | Mapping servlet: 'MyBeautifulServlet' to [/mySuperApp/service1/*, /mySuperApp/service2/*]
【讨论】:
您只需要一个 Dispatcherservlet,其根上下文路径设置为您想要的(可以是 / 或 mySuperApp)。
通过声明多个@RequestMaping,您将能够使用相同的 DispatcherServlet 提供不同的 URI。
这是一个例子。使用 @RequestMapping("/service1") 和 @RequestMapping("/service2") 将 DispatcherServlet 设置为 /mySuperApp 会暴露以下端点:
/mySuperApp/service1
/mySuperApp/service2
单个 servlet 具有多个上下文不是 Servlet 规范的一部分。单个 servlet 不能从多个上下文中提供服务。
您可以将多个值映射到您的请求映射。
@RequestMapping({"/context1/service1}", {"/context2/service1}")
我没有看到任何其他方式。
【讨论】:
您可以使用 'server.contextPath' 属性占位符来设置整个 Spring Boot 应用程序的上下文路径。 (例如server.contextPath=/live/path1)
此外,您可以设置将应用于所有方法的类级别上下文路径,例如:
@RestController
@RequestMapping(value = "/testResource", produces = MediaType.APPLICATION_JSON_VALUE)
public class TestResource{
@RequestMapping(method = RequestMethod.POST, value="/test", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TestDto> save(@RequestBody TestDto testDto) {
...
有了这个结构,你可以使用/live/path1/testResource/test来执行save方法。
【讨论】: