Java 访问 JSP 中的常量(没有 scriptlet)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/122254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
accessing constants in JSP (without scriptlet)
提问by Dónal
I have a class that defines the names of various session attributes, e.g.
我有一个定义各种会话属性名称的类,例如
class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
I would like to use these constants within a JSP to test for the presence of these attributes, something like:
我想在 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>
But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <c:set>
, but again I'm struggling to find the correct syntax.
但我似乎无法正确使用语法。另外,为了避免在多个地方重复上面相当冗长的测试,我想将结果分配给本地(页面范围)变量,并改为引用它。我相信我可以用 来做到这一点<c:set>
,但我再次努力寻找正确的语法。
UPDATE:Further to the suggestion below, I tried:
更新:根据以下建议,我尝试了:
<c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered
这不起作用。因此,我尝试替换常量的字面值。我还将常量添加到页面的内容中,因此我可以在呈现页面时验证常量的值
<c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....
这工作正常,它在页面上打印了预期值“current.user”。我无法解释为什么使用 String 文字有效,但当两者似乎具有相同的值时,对常量的引用却无效。帮助.....
采纳答案by Athena
It's not working in your example because the ATTR_CURRENT_USER
constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the unstandard tag library.
它在您的示例中不起作用,因为该ATTR_CURRENT_USER
常量对 JSTL 标记不可见,JSTL 标记期望属性由 getter 函数公开。我还没有尝试过,但是暴露常量的最干净的方法似乎是unstandard tag library。
ETA: Old link I gave didn't work. New links can be found in this answer: Java constants in JSP
ETA:我提供的旧链接无效。可以在此答案中找到新链接:JSP 中的 Java 常量
Code snippets to clarify the behavior you're seeing: Sample class:
阐明您所看到的行为的代码片段:示例类:
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;
}
}
Snippet of the JSP page, showing sample usage:
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 />
This outputs:
这输出:
Using scriptlets
使用小脚本
Constants.ATTR_CURRENT_USER
常量.ATTR_CURRENT_USER
current.user
当前用户
Session[Constants.ATTR_CURRENT_USER]
会话[常量.ATTR_CURRENT_USER]
Me
我
Using JSTL
使用 JSTL
Constants.getATTR_CURRENT_USER_FUNC()
Constants.getATTR_CURRENT_USER_FUNC()
current.user
当前用户
Session[Constants.getATTR_CURRENT_USER_FUNC()]
会话[Constants.getATTR_CURRENT_USER_FUNC()]
Me
我
Constants.ATTR_CURRENT_USER
常量.ATTR_CURRENT_USER
回答by Matt N
First, your syntax had an extra "]" which was causing an error.
首先,您的语法有一个额外的“]”,这导致了错误。
To fix that, and to set a variable you would do this:
要解决这个问题,并设置一个变量,你可以这样做:
<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>
回答by Ramesh PVK
Plugin a Custom EL Resolver to the EL resolver chain, which will resolve the constants. An EL Resolver is Java class extending javax.el.ELResolverclass.
将自定义 EL 解析器插入 EL 解析器链,这将解析常量。EL Resolver 是扩展javax.el.ELResolver类的Java类。
Thanks,
谢谢,
回答by Edgar
the topic is quite old, but anyway..:)
这个话题已经很老了,但无论如何..:)
I found nice solution to have Constants available through JSTL. You should prepare a map using reflection and put it wherever you want.
我找到了一个很好的解决方案,可以通过 JSTL 使用常量。您应该使用反射准备一张地图并将其放在您想要的任何位置。
The map will always contain all the constants you define in Constants class. You can put it into ServletContext using listener and enjoy constants in JSTL like:
地图将始终包含您在 Constants 类中定义的所有常量。您可以使用侦听器将其放入 ServletContext 并享受 JSTL 中的常量,例如:
${CONSTANTS["CONSTANT_NAME_IN_JAVA_CLASS_AS_A_STRING"]}
CONSTANTS here is a key you used putting map into Context :-)
CONSTANTS 是您将地图放入上下文时使用的键:-)
The following is a piece of my code building a map of the constant fields:
以下是我构建常量字段映射的一段代码:
Map<String, Object> map = new HashMap<String, Object>();
Class c = Constants.class;
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
int modifier = field.getModifiers();
if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier) && Modifier.isFinal(modifier)) {
try {
map.put(field.getName(), field.get(null));//Obj param of get method is ignored for static fields
} catch (IllegalAccessException e) { /* ignorable due to modifiers check */ }
}
}
回答by daniel.deng
You can define Constants.ATTR_CURRENT_USER as a variable with c:set,just as below:
您可以使用 c:set 将 Constants.ATTR_CURRENT_USER 定义为变量,如下所示:
<c:set var="ATTR_CURRENT_USER" value="<%=Constants.ATTR_CURRENT_USER%>" />
<c:if test="${sessionScope[ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
回答by Roger Keays
Static properties aren't accessible in EL. The workaround I use is to create a non-static variable which assigns itself to the static value.
在 EL 中无法访问静态属性。我使用的解决方法是创建一个非静态变量,该变量将自身分配给静态值。
public final static String MANAGER_ROLE = 'manager';
public String manager_role = MANAGER_ROLE;
I use lombok to generate the getter and setter so that's pretty well it. Your EL looks like this:
我使用 lombok 来生成 getter 和 setter,这样就很好了。你的 EL 看起来像这样:
${bean.manager_role}
Full code at http://www.ninthavenue.com.au/java-static-constants-in-jsp-and-jsf-el
完整代码位于http://www.ninthavenue.com.au/java-static-constants-in-jsp-and-jsf-el
回答by hb5fa
I am late to the discussion, but my approach is a little different. I use a custom tag handler to give JSP pages the constant values (numeric or string) it needs. Here is how I did it:
我迟到了讨论,但我的方法有点不同。我使用自定义标记处理程序为 JSP 页面提供它需要的常量值(数字或字符串)。这是我如何做到的:
Supposed I have a class that keeps all the constants:
假设我有一个保留所有常量的类:
public class AppJspConstants implements Serializable {
public static final int MAXLENGTH_SIGNON_ID = 100;
public static final int MAXLENGTH_PASSWORD = 100;
public static final int MAXLENGTH_FULLNAME = 30;
public static final int MAXLENGTH_PHONENUMBER = 30;
public static final int MAXLENGTH_EXTENSION = 10;
public static final int MAXLENGTH_EMAIL = 235;
}
I also have this extremely simple custom tag:
我还有这个非常简单的自定义标签:
public class JspFieldAttributes extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().setAttribute("maxlength_signon_id", AppJspConstants.MAXLENGTH_SIGNON_ID);
getJspContext().setAttribute("maxlength_password", AppJspConstants.MAXLENGTH_PASSWORD);
getJspContext().setAttribute("maxlength_fullname", AppJspConstants.MAXLENGTH_FULLNAME);
getJspContext().setAttribute("maxlength_phonenumber", AppJspConstants.MAXLENGTH_PHONENUMBER);
getJspContext().setAttribute("maxlength_extension", AppJspConstants.MAXLENGTH_EXTENSION);
getJspContext().setAttribute("maxlength_email", AppJspConstants.MAXLENGTH_EMAIL);
getJspBody().invoke(null);
}
}
Then I have a StringHelper.tld. Inside, I have this :
然后我有一个 StringHelper.tld。在里面,我有这个:
<tag>
<name>fieldAttributes</name>
<tag-class>package.path.JspFieldAttributes</tag-class>
<body-content>scriptless</body-content>
<info>This tag provide HTML field attributes that CCS is unable to do.</info>
</tag>
On the JSP, I include the StringHelper.tld the normal way:
在 JSP 上,我以正常方式包含 StringHelper.tld:
<%@ taglib uri="/WEB-INF/tags/StringHelper.tld" prefix="stringHelper" %>
Finally, I use the tag and apply the needed values using EL.
最后,我使用标记并使用 EL 应用所需的值。
<stringHelper:fieldAttributes>
[snip]
<form:input path="emailAddress" cssClass="formeffect" cssErrorClass="formEffect error" maxlength="**${maxlength_email}**"/>
<form:errors path="emailAddress" cssClass="error" element="span"/>
[snip]
</stringHelper:fieldAttributes>