它在您的示例中不起作用,因为该
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" 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()]
我



