accessing constants in JSP (without scriptlet)
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.
ETA: Old link I gave didn't work. New links can be found in this answer: Java constants in JSP
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:
<%-- 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
current.user
Session[Constants.ATTR_CURRENT_USER]
Me
Using JSTL
Constants.getATTR_CURRENT_USER_FUNC()
current.user
Session[Constants.getATTR_CURRENT_USER_FUNC()]
Me
Constants.ATTR_CURRENT_USER
You can define Constants.ATTR_CURRENT_USER as a variable with c:set,just as below:
<c:set var="ATTR_CURRENT_USER" value="<%=Constants.ATTR_CURRENT_USER%>" />
<c:if test="${sessionScope[ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>