如果用户被记录(使用JSTL <if>语句)并显示用户名?</if>,如何检入JSP

时间:2014-01-24 09:42:40

标签: java jsp servlets jstl

我知道SO上有许多类似的问题 - 大多数都是指用servlet过滤器实现这个概念。

我使用基于表单的声明式安全方法。并且,当一些用户在登录表单上输入他(或她)的凭证(用户名和密码)时,他被重定向到某个/安全的jsp页面。该页面内容的一部分是:

Hello <%=request.getUserPrincipal().getName().toString()%>
    You are able to view this page because you are authorized user.

现在,如果用户已登录,我想显示他/她的用户名,无论是否有安全的jsp页面。像这样:

<c:if test="${statement that checks if some user is logged in}">
   User: ${username of the logged user here}
</c:if>

修改 我还想用适当的JSTL命令替换JSP scriptlet部分:<%=request.getUserPrincipal().getName().toString()%>

2 个答案:

答案 0 :(得分:5)

<c:if test="${not empty pageContext.request.userPrincipal}">
    User: <c:out value="${pageContext.request.userPrincipal.name}" />
</c:if>

使用c:out正确转义打印值并防止XSS攻击。

答案 1 :(得分:2)

我在两种情况下都缺少pageContext对象,request本身不是JSP页面中的隐式对象。

<c:if test="${not empty pageContext.request.userPrincipal}">
    User <c:out value="${pageContext.request.userPrincipal.name}" />
</c:if>

<%=request.getUserPrincipal().getName().toString()%>的等效JSTL为:<c:out value="${pageContext.request.userPrincipal.name}"/>