spring - 在JSP页面中获取用户名。主体.用户名不起作用

标签 spring jsp spring-mvc spring-security jspx

我有一个完全正常工作的 Spring Security。我需要在页面上打印用户名, Controller 不适合,因为该页面是其他页面模板的一部分。

我尝试了很多与此类似的选项:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
    xmlns:form="http://www.springframework.org/tags/form"
    xmlns:display="http://displaytag.sf.net" version="2.0"
    xmlns:sec="http://www.springframework.org/security/tags">
    <jsp:directive.page contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" session="true" />
    <jsp:output doctype-root-element="html"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        omit-xml-declaration="true" />
    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body>
...
<sec:authorize access="isAuthenticated()">
    <sec:authentication property="principal.username"></sec:authentication>
</sec:authorize>
...
</body>
    </html>
</jsp:root>

但是代码不打印,也没有错误。 我尝试对不同的用户进行身份验证,并将代码放在不同的页面上,但这对我没有帮助。 如何解决?

最佳答案

试试这个,这对我有用。

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authorize var="loggedIn" access="isAuthenticated()" />
<c:choose>
    <c:when test="${loggedIn}">
            <%= request.getUserPrincipal().getName() %>        
    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>

关于spring - 在JSP页面中获取用户名。主体.用户名不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17812818/

相关文章:

Spring AOP : How to read path variable value from URI template in aspect?

java - 如何在整个 Spring Boot 项目中将所有字符串变量设置为 upperCase()

java - 无法在 Spring MVC @Controller 类中访问 HttpSession

javascript - $resource.save 使用 "Resource"而不是简单的 ID 进行响应

java - Spring 数据 Autowiring 数据库连接无法通过 JUnit 测试

java - 如何模拟 object.getMap().get ("String_Key_to_return_Object")

java - 使用 MockMvc 测试 @preAuthorize(custom_implementation)

java - 将图表添加到缓冲区

java - 在eclipse中创建jsp文件时遇到问题

java - java httpssession的生命周期