spring security. display user name on every page

前端 未结 3 1520
执笔经年
执笔经年 2021-02-04 21:18

I want to store user information after logging in and to display my login and username on every page (using jsp). How can I get access in my jsp views to the session bean that w

3条回答
  •  悲哀的现实
    2021-02-04 21:31

    I'm assuming you are using spring security. After successful login put the UserDetails object in the session like so (This is usually the controller where you would forward if login was successfull)

    Object principal = SecurityContextHolder.getContext()
         .getAuthentication().getPrincipal();
    HttpSession session = request.getSession(true); //create a new session
    
    // put the UserDetails object here.
    session.setAttribute("userDetails", principal);
    

    In your JSP you can access the UserDetails object, like so:

    Welcome ${userDetails.username}
    

提交回复
热议问题