[英]How to check in JSP if user is logged (using JSTL <if> statement), and display username?
I am aware there are many similar questions on SO - most of them referring to implement this concept with servlet filters. 我知道在SO上有许多类似的问题 - 大多数都是指用servlet过滤器实现这个概念。
I am using form based, declarative security approach. 我使用基于表单的声明式安全方法。 And, when some user, on login form enters his(or her) credentials (username and password), he is being redirected to certain/secured jsp page.
并且,当一些用户在登录表单上输入他(或她)的凭证(用户名和密码)时,他被重定向到某个/安全的jsp页面。 Part of that page content is:
该页面内容的一部分是:
Hello <%=request.getUserPrincipal().getName().toString()%>
You are able to view this page because you are authorized user.
Now, if user is logged in, I would like display his/her username, no matter if its secured jsp page or not. 现在,如果用户已登录,我想显示他/她的用户名,无论是否有安全的jsp页面。 Something like this:
像这样的东西:
<c:if test="${statement that checks if some user is logged in}">
User: ${username of the logged user here}
</c:if>
EDIT I would also like to replace JSP scriptlet part: <%=request.getUserPrincipal().getName().toString()%>
with appropriate JSTL command. 编辑我还想用适当的JSTL命令替换JSP scriptlet部分:
<%=request.getUserPrincipal().getName().toString()%>
。
<c:if test="${not empty pageContext.request.userPrincipal}">
User: <c:out value="${pageContext.request.userPrincipal.name}" />
</c:if>
Use c:out
to correctly escape printed values and prevent XSS attacks. 使用
c:out
正确地转义打印值并防止XSS攻击。
I was missing pageContext
object in both situations, request
by itself is not implicit object in JSP page. 我在两种情况下都缺少
pageContext
对象, request
本身不是JSP页面中的隐式对象。
<c:if test="${not empty pageContext.request.userPrincipal}">
User <c:out value="${pageContext.request.userPrincipal.name}" />
</c:if>
And JSTL equivalent for <%=request.getUserPrincipal().getName().toString()%>
is: <c:out value="${pageContext.request.userPrincipal.name}"/>
和
<%=request.getUserPrincipal().getName().toString()%>
JSTL等价物是: <c:out value="${pageContext.request.userPrincipal.name}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.