Arian
Arian

Reputation: 7719

Get user in a Rest Controller class instead of each controller method

I have a @RestController with bunch of Rest endpoints as methods.

@RequestMapping(path="",method=RequestMethod.POST)
public void create(Principal principal) {
    String userName = principal.getName();
    User user = UsersRepository.loadUser(userName);
    //....
}

@RequestMapping(path="/{groupId}",method=RequestMethod.DELETE)
public void deleteGroup(@PathVariable String groupId, Principal principal) {
    String userName = principal.getName();
    User user = UsersRepository.loadUser(userName);
    //....
}

In each method I have to repeat this code:

    String userName = principal.getName();
    User user = UsersRepository.loadUser(userName);

Is there a way not to repeat this in each method and get it in the class, and consume it in each method ?

Upvotes: 0

Views: 68

Answers (1)

davidxxx
davidxxx

Reputation: 131336

1) Very basic but why not simply extract it in a private method :

public User getUser(Principal principal){
  String userName = principal.getName();
  User user = UsersRepository.loadUser(userName);
  //....
  return user;
}

You could write so :

@RequestMapping(path="",method=RequestMethod.POST)
public void create(Principal principal) {
    User user = getUser(principal);
    //....
}

2) More advanced : you could use a Spring interceptor that reads in the request, loads the user and wires it in a bean with a request scope.

Upvotes: 3

Related Questions