For a simple RESTful JSON api implemented in Spring MVC, can I use Bean Validation (JSR-303) to validate the path variables passed into the handler method?
For examp
Instead of using @PathVariable, you can take advantage of Spring MVC ability to map path variables into a bean:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/{id}")
public void get(@Valid GetDto dto) {
// dto.getId() is the path variable
}
}
And the bean contains the actual validation rules:
@Data
public class GetDto {
@Min(1) @Max(99)
private long id;
}
Make sure that your path variables ({id}
) correspond to the bean fields (id
);