如何在jsp中显示当前用户?

pie*_*età 1 logging spring-mvc spring-security

我是Spring Mvc的新手,我刚刚使用spring security完成了用户身份验证,我希望已登录的用户显示在主页("userX已连接"之类的消息)并记录所有用户谁登录.你能帮助我吗 ?有任何想法吗 ?

Rob*_*nch 8

请求属性

建议的做法是向请求添加带有用户名值的请求属性.优点是,这使您与Spring Security脱钩.如果您决定删除Spring Security,则您的视图不会受到影响.在Spring MVC中,您可以使用以下内容填充请求属性:

@RequestMapping("/home")
public String home(Principal principal, Model model) {
    if(principal != null) {
        model.addAttribute("username", principal.getName());
    }
}
Run Code Online (Sandbox Code Playgroud)

在标准的Servlet环境中(即不使用Spring MVC),您可以简单地使用

if(principal != null) {
    httpServletRequest.setAttribute("username", principal.getName()); 
}
Run Code Online (Sandbox Code Playgroud)

然后在JSP中,您可以使用以下内容显示它:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${username}"/>
Run Code Online (Sandbox Code Playgroud)

注意:使用标记库输出用户名以避免XSS问题非常重要.如果不将$ {username}放在taglib中或确保正确转义值,请不要使用它.

大多数时候,用户希望能够将用户名添加到每个页面.您可以使用@ModelAttribute&@ControllerAdvice在Spring MVC 3.2+中轻松完成此操作.例如:

@ControllerAdvice
public class UserControllerAdvice {
    @ModelAttribute("username")
    public String username(Principal principal) {
        return principal == null ? null : principal.getName();
    }
}
Run Code Online (Sandbox Code Playgroud)

从HttpServletRequest访问

Spring Security将用户公开为标准的Principal HttpServletRequest.getUserPrincipal()(这实际上是我们在Spring MVC示例中解析Principal的方式)和HttpServletRequest.getRemoteUser()方法.这意味着您还可以在HttpServletRequest中访问JSP中的用户.这意味着您还可以使用:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${pageContext.request.remoteUser}"/>
Run Code Online (Sandbox Code Playgroud)

Spring Security taglib

另一种方法是使用Spring Security JSP标记库(如前所述).例如

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="name"/>
Run Code Online (Sandbox Code Playgroud)

记录身份验证尝试

您可以通过实现ApplicationListener并将其作为bean公开来记录身份验证尝试.Spring Security提供了一个名为LoggerListener的实现.要使用它,请在配置中添加以下内容:

<b:bean class="org.springframework.security.authentication.event.LoggerListener"/>
Run Code Online (Sandbox Code Playgroud)

您也可以提供自己的实现.以下是它的外观概述:

public class MyListener implements ApplicationListener<AbstractAuthenticationEvent> {

    public void onApplicationEvent(AbstractAuthenticationEvent event) {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)