代码之家  ›  专栏  ›  技术社区  ›  JackTheKnife

Spring@RequestMapping注释到不同的位置

  •  0
  • JackTheKnife  · 技术社区  · 7 年前

    http://localhost/ - display Welcome page
    http://localhost/api/v1/getUser - do the `getUser` controller part
    http://localhost/api/v1/addUser - do the `addUser` controller part
    

    所以我为那个部分创建了简单的控制器

    @RestController
    public class restController {
    
        @GetMapping("/")
        public String restAPI() {
    
                return "Welcome Page";
        }
    
        @RequestMapping("/api/v1")
        @PostMapping("/addUser")
        @ResponseBody
        public User addUser(@RequestBody User user) {
             //do the stuff
        }
    
    
        @RequestMapping("/api/v1")
        @GetMapping("/getUser")
        @ResponseBody
        public User getUser(@RequestBody User user) {
             //do the stuff
        }
    

    我得到的只是欢迎页面,但无法访问任何端点。当我卸下负责的部件时 restAPI() 我能够到达这两个终点。

    有混合的方法吗 @RequestMapping

    1 回复  |  直到 7 年前
        1
  •  1
  •   Chris    7 年前

    最好的解决方案是创建如下两个控制器:

    @RestController
    @RequestMapping("/")
    public class HomeController {
    
        @GetMapping
        public String restAPI() {
    
            return "Welcome Page";
        }
    }
    

    如果您将GET请求发送到 http://localhost/ 您将显示欢迎页面。

    以及:

    @RestController
    @RequestMapping("/api/v1")
    public class UserController {
    
        @PostMapping
        public User addUser(@RequestBody User user) {
             //do the stuff
        }
    
        @GetMapping
        public User getUser(@RequestBody User user) {
            //do the stuff
        }
    }
    

    通过发送邮件或到达 http://localhost/api/v1/ 并创建或获取一个用户。