【问题标题】:How to attach a word before each request in spring mvc?如何在spring mvc中的每个请求之前附加一个单词?
【发布时间】:2020-02-12 07:27:19
【问题描述】:

我有一个 spring mvc 控制器,它有很多方法。 在所有方法中,我都以/api 开头,后跟实际单词。 目前我必须手动输入/api/request1/api/request2等等。有没有办法只提及我的请求名称并自动附加/api

控制器:

package com.json.host;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {
    @GetMapping(value="/api/host")
    public String returnText() {
        return "hello";
    }
}

【问题讨论】:

  • 你的意思是像@GetMapping(value="/host")这样的东西吗?

标签: java spring rest spring-boot spring-mvc


【解决方案1】:

您可以在类级别添加@RequestMapping("/api"),然后在方法级别省略它。

所以这样的事情应该可以解决问题:

@RestController
@RequestMapping("/api")
public class Test {
    @GetMapping(value="/host")
    public String returnText() {
        return "hello";
    }
}

也记录在 javadoc 中:

在类型级别和方法级别都支持!使用时 在类型级别,所有方法级别的映射都继承这个主要的 映射,针对特定的处理程序方法缩小范围。

(https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html):

【讨论】:

    【解决方案2】:

    您可以在类级别添加@RequestMapping("/api"),并且在您的方法映射中只有其余的 url。

    package com.json.host;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @RestController
    @RequestMapping("/api")
    public class Test {
        @GetMapping(value="/host")
        public String returnText() {
            return "hello";
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要在类级别添加@RequestMapping(value = "/api")。它会自动附加到方法级别的请求中。

      @RestController
      @RequestMapping(value = "/api")
      public class Test {
      
          @GetMapping(value="/request1")
          public String returnText() {
              return "hello";
          }
      
          @GetMapping(value="/request2")
          public String returnText2() {
              return "hello2";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 2017-11-26
        • 2015-11-27
        • 1970-01-01
        • 2021-05-08
        相关资源
        最近更新 更多