【问题标题】:What is wrong in this Spring Boot controller method annotation? (the path of the request is defined at class level and the path variable at method)这个 Spring Boot 控制器方法注释有什么问题? (请求的路径在类级别定义,路径变量在方法中定义)
【发布时间】:2021-12-30 17:20:42
【问题描述】:

我正在开发一个 Spring Boot 项目,我发现控制器类方法存在以下问题。

我有这个简单的控制器类:

@RestController
@RequestMapping("/api/admin/usertype")
@Log
public class UserTypeControllerAdmin {
    
    @Autowired
    UserTypeService userTypeService;
    
    @ApiOperation(
              value = "Retrieve the details of a specific user type by the type name", 
              notes = "",
              produces = "application/json")
    @GetMapping(value = "/", produces = "application/json")
    public ResponseEntity<UserType> getUSerTypeByName(@PathVariable("usertype") String userType) throws NotFoundException  {
        log.info(String.format("****** Retrieve the details of user type having name %s *******", userType));
        
        UserType retrievedUserType = userTypeService.getUserTypeByName(userType);
        
        return new ResponseEntity<UserType>(retrievedUserType, HttpStatus.OK);
            
    }

}

如您所见,控制器类被此映射注解:

@RequestMapping("/api/admin/usertype")

现在我有了这个 getUSerTypeByName() 控制器类方法,它应该处理像 /api/admin/usertype/ADMIN 这样的 GET 请求,其中 ADMIN是 @PathVariable("usertype") String userType

的值

问题是执行像前一个请求一样的请求,它没有进入前一个控制器方法,Spring Boot 返回 404 错误。

为什么?我的注释有什么问题?我错过了什么?我该如何尝试修复它?

【问题讨论】:

    标签: java spring spring-boot spring-mvc


    【解决方案1】:

    问题是usertype 未在此处的路径中定义:

    @GetMapping(value = "/", produces = "application/json")
    

    您需要告诉 Spring 在哪里可以找到 @PathVariable("usertype")。所以这样的事情会起作用

    @GetMapping(value = "/{usertype}", produces = "application/json")
    

    这是一个 tutorial 关于在 Spring Boot 中使用路径变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多