在JSP中访问常量(没有scriptlet)
时间:2020-03-06 14:36:39 来源:igfitidea点击:
我有一个定义各种会话属性名称的类,例如
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文字可以工作,但是当两者看起来具有相同的值时,对常量的引用却不起作用。帮助.....
解决方案
首先,语法中有一个额外的"]",这会导致错误。
要解决此问题并设置变量,请执行以下操作:
<c:set var="nullUser"
scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
<c:if test="${nullUser}">
<h2>First Test</h2>
</c:if>
<c:if test="${nullUser}">
<h2>Another Test</h2>
</c:if>
它在示例中不起作用,因为JSTL标记不可见" ATTR_CURRENT_USER"常量,该标记期望属性由getter函数公开。我还没有尝试过,但是暴露常量的最干净的方法似乎是不标准的标记库。
ETA:我给的旧链接无效。在此答案中可以找到新的链接:JSP中的Java常量
代码段可以澄清我们所看到的行为:
范例类别:
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]
我
Constants.getATTR_CURRENT_USER_FUNC()
当前用户
会话[Constants.getATTR_CURRENT_USER_FUNC()]
我

