【问题标题】:Multiple servlet mappings in Spring BootSpring Boot 中的多个 servlet 映射
【发布时间】:2016-06-30 05:29:36
【问题描述】:

有没有办法通过属性“上下文路径”为同一个 Spring Boot MVC 应用程序设置许多映射?我的目标是避免为 uri 映射创建许多“Dispatcherservlet”。

例如:

servlet.context-path =/, /context1, context2

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

    您可以创建返回 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/*]
    

    【讨论】:

      【解决方案2】:

      您只需要一个 Dispatcherservlet,其根上下文路径设置为您想要的(可以是 / 或 mySuperApp)。

      通过声明多个@RequestMaping,您将能够使用相同的 DispatcherServlet 提供不同的 URI。

      这是一个例子。使用 @RequestMapping("/service1") 和 @RequestMapping("/service2") 将 DispatcherServlet 设置为 /mySuperApp 会暴露以下端点:

      /mySuperApp/service1

      /mySuperApp/service2

      单个 servlet 具有多个上下文不是 Servlet 规范的一部分。单个 servlet 不能从多个上下文中提供服务。

      您可以将多个值映射到您的请求映射。

      @RequestMapping({"/context1/service1}", {"/context2/service1}")

      我没有看到任何其他方式。

      【讨论】:

      • Daniel 我不想映射 uri 控制器,我的目标是为同一个 servlet 提供许多上下文映射。
      • 这不是 Servlet 规范的一部分。单个 servlet 不能从多个上下文服务器。您可以做的是将多个值映射到您的请求映射。 @RequestMapping({"/context1/service1}", {"/context2/service1}") 我没有看到任何其他方式。
      • 如果查看 web.xml 描述符,我们可以添加标签servlet*.jsp-pattern> servlet/url
      • 那么,在 Spring Boot 中该怎么做呢?
      • Spring boot 不会公开该配置。
      【解决方案3】:

      您可以使用 '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方法。

      【讨论】:

      • 但是我如何为同一个 servlet 映射多个映射?这是我的问题。
      • Darshan,我们可以在不创建新类的情况下使用 Spring Boot 属性吗?
      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 2017-11-13
      • 2018-06-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多