Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading