Question

I want to manage users projects through a JSON API and I'd like to use a relative path controller. Like this:

@RequestMapping(value="/users/{userId}/projects",
    headers="Accept=application/json")
@Controller
public class UserProjectsController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(method=RequestMethod.GET)
    public @ResponseBody Object getAllUserProjects(@PathVariable String userId) {
        User user = userRepository.findById(userId);
        if (user == null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        return user.getGivenProjects();
    }
}

I'll add numerous methods and every time I'll have to check if the user exists. Instead of adding that piece of code:

User user = userRepository.findById(userId);
if (user == null) {
    return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}

... at starting of every method, I'd like to create a custom annotation which will return a 404 if the user doesn't exist.

I found this tutorial to do that. Is this really as complicated as described? Do you know any other solution? (I'd like to avoid writing 2 classes and more than 50 lines of code only to annotate 4 lines.)

Thank you.

Was it helpful?

Solution

I firstly assume that this check has nothing to do with Security, does it?

I think WebArgumentResolver won't fit your needs. Returning a 404 status might be complicated.

Maybe a custom interceptor can be a better solution. It will be called in every request to your controllers. There you can examine the handler object in order to see if it has a parameter called userId annotated with @PathVariable, for example. Then, you can do the check and use response object for returning a 404 if it's necessary.

Another option would be create a custom @Aspect, but we maybe are overcomplicating the problem. So first, try the previous solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top