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:
<%@ 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.
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…..
It’s not working in your example because the
ATTR_CURRENT_USERconstant 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:
Snippet of the JSP page, showing sample usage:
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