【问题标题】:spring security. display user name on every page春季安全。在每个页面上显示用户名
【发布时间】:2011-04-07 23:42:59
【问题描述】:

我想在登录后存储用户信息并在每个页面上显示我的登录名和用户名(使用 jsp)。如何在我的 jsp 视图中访问将存储已登录用户信息的会话 bean?

【问题讨论】:

    标签: spring security jsp model-view-controller spring-security


    【解决方案1】:

    使用authentication tag

    这个标签允许访问当前 身份验证对象存储在 安全上下文。它呈现一个 对象的属性直接在 JSP。因此,例如,如果委托人 Authentication 的属性是 Spring Security 的实例 UserDetails 对象,然后使用 将 呈现当前用户的名字。

    当然,没必要使用 这类事情的 JSP 标签和 有些人喜欢保持尽可能少 视图中尽可能的逻辑。你可以 访问 Authentication 对象 你的 MVC 控制器(通过调用 SecurityContextHolder.getContext().getAuthentication()) 并将数据直接添加到您的 视图渲染的模型。

    【讨论】:

      【解决方案2】:

      这与When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean? 几乎重复。 Spring认可的方法是

      final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
      

      但链接的讨论有其他选择。

      【讨论】:

        【解决方案3】:

        我假设您使用的是 Spring Security。成功登录后,像这样将 UserDetails 对象放入会话中(这通常是登录成功时您将转发的控制器)

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

        在您的 JSP 中,您可以访问 UserDetails 对象,如下所示:

        <span class="message">Welcome ${userDetails.username}</span>
        

        【讨论】:

        • 将 lvl 降低到会话对象而不是使用应该为您处理它的 Spring 功能真的是个好主意吗?
        猜你喜欢
        • 2011-01-12
        • 2020-02-25
        • 2018-01-14
        • 2015-08-15
        • 2013-12-22
        • 2014-04-08
        • 1970-01-01
        相关资源
        最近更新 更多