D
D
DeNissss44442021-05-20 10:35:37
Java
DeNissss4444, 2021-05-20 10:35:37

How to make the username displayed on every page of the site, and not just on the main one?

I have user authentication that displays his name if he entered the site under his login, but if he is not registered on the site, then Anonymous writes. I display this check on the side of the menu on the site. It turns out I wrote this in the main controller, which is responsible for the start page of the site. The problem is that when I go through the menu to another section of the site, for example, a blog, then naturally there is no check in the menu and nothing is displayed. I also need to display the username or anonymous in the menu on any page of the site. Of course, I can write this check in each controller that is responsible for different sections of the site, but something tells me that this is not the right solution and it should be different. Can anyone advise what is the best way to handle this situation?

@Controller
public class MainController {

    @GetMapping("/index")
    public String homePage(@AuthenticationPrincipal User user, Model model){
        if(user != null){
            model.addAttribute("user", user.getUsername());
            return "/index";
        } else {
            model.addAttribute("user", "Аноним");
            return "/index";
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-05-20
@DeNissss4444

Good afternoon!
It might not be the best solution, but I would do it like this:
I would use@ControllerAdvice

@ControllerAdvice
public class GlobalControllerAdvice {

    // Текущий авторизованный пользователь
    @ModelAttribute("user")
    public User getUserProfile(
            @AuthenticationPrincipal UserDetails currentUser
    ) {
        if(
                SecurityContextHolder.getContext().getAuthentication() != null &&
                SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
                !(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)

        ) {
            return (User) userService.findUserByEmail(currentUser.getUsername());
        } else {
            return null;
        }

    }

}

Accordingly, if the user is authorized, then you will receive user, and if not, then null.
Well, further in any template you can display information about the user WITHOUT using this code for each controller:
if(user != null){
            model.addAttribute("user", user.getUsername());
            return "/index";
        } else {
            model.addAttribute("user", "Аноним");
            return "/index";
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question