简体   繁体   中英

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)

I am working on a Spring Boot project and I am finding the following problem with a controller class method.

I have this simple controller class:

@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);
            
    }

}

As you can see controller class is annotated by this mapping:

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

Now I have this getUSerTypeByName() controller class method that should handle GET request like /api/admin/usertype/ADMIN where ADMIN is the value of the @PathVariable("usertype") String userType

The problem is that performing a request like the previous one it doesn't enter into the previous controller method and Spring Boot return a 404 error.

Why? What is wrong in my annotation? What am I missing? How can I try to fix it?

The problem is a usertype is not defined in the paths here:

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

You need to tell Spring where to find the @PathVariable("usertype") . So something like this would work

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

Here's a tutorial about using path variables in Spring Boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM