FeCH
FeCH

Reputation: 133

Check if user is logged in Spring MVC

I want to get the userName information if they're logged in. If user is not logged in, the if statement should skip this action. I thought implies is what i should be using but its currently throwing me null pointer when user is not logged in.

@RequestMapping(value = "/", method = RequestMethod.GET)
public String displayHomePage(Model model, Principal user) {
    if(!user.implies(null)){
        String name = user.getName();
        User currentUser = userService.getUserByName(name);
    }

Upvotes: 0

Views: 3265

Answers (1)

holmis83
holmis83

Reputation: 16604

The Principal parameter variable will be null if the user is not logged in, so check it for null like this:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String displayHomePage(Model model, Principal user) {
    if (user != null) {
        String name = user.getName();
        // ...

Upvotes: 6

Related Questions