小编典典

在JSP中访问常量(没有scriptlet)

jsp

我有一个定义各种会话属性名称的类,例如

class Constants {
    public static final String ATTR_CURRENT_USER = "current.user";
}

我想在JSP中使用这些常量来测试这些属性的存在,例如:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>

<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
    <%-- Do somthing --%>
</c:if>

但是我似乎无法正确理解该语法。另外,为避免在多个地方重复上述相当冗长的测试,我想将结果分配给局部(页面范围)变量,然后引用该变量。我相信我可以用做到这一点<c:set>,但是我又在努力寻找正确的语法。

更新: 根据下面的建议,我尝试了:

<c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />

这没有用。因此,我尝试用常量的字面值代替。我还将常量添加到页面的内容中,因此可以在呈现页面时验证常量的值

<c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>

这工作正常,并在页面上打印了预期值“
current.user”。我无所适从地解释了为什么使用String文字可以工作,但是当两者看起来具有相同的值时,对常量的引用却不能。帮帮我.....


阅读 288

收藏
2020-06-08

共1个答案

小编典典

它在您的示例中不起作用,因为该ATTR_CURRENT_USER常量对于JSTL标记不可见,因为JSTL标记期望属性由getter函数公开。我还没有尝试过,但是暴露常量的最干净的方法似乎是非标准标记库

ETA:我给的旧链接无效。在此答案中可以找到新的链接:

代码段来阐明您所看到的行为:示例类:

package com.example;

public class Constants
{
    // attribute, visible to the scriptlet
    public static final String ATTR_CURRENT_USER = "current.user";

    // getter function;
    // name modified to make it clear, later on, 
    // that I am calling this function
    // and not accessing the constant
    public String getATTR_CURRENT_USER_FUNC()
    {
        return ATTR_CURRENT_USER;
    }


}

JSP页面的片段,显示示例用法:

<%-- Set up the current user --%>
<%
    session.setAttribute("current.user", "Me");
%>

<%-- scriptlets --%>
<%@ page import="com.example.Constants" %>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<%=Constants.ATTR_CURRENT_USER%> <br />
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>

<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="cons" class="com.example.Constants" scope="session"/>

<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<h3>Constants.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/>
<%--
Commented out, because otherwise will error:
The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.

<h3>cons.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
--%>
<hr />

输出:

使用脚本

常数.ATTR_CURRENT_USER

当前用户

会话[Constants.ATTR_CURRENT_USER]


使用JSTL

Constants.getATTR_CURRENT_USER_FUNC()

当前用户

会话[Constants.getATTR_CURRENT_USER_FUNC()]

常数.ATTR_CURRENT_USER


2020-06-08