Note that there are some explanatory texts on larger screens.

plurals
  1. POaccessing constants in JSP (without scriptlet)
    text
    copied!<p>I have a class that defines the names of various session attributes, e.g.</p> <pre><code>class Constants { public static final String ATTR_CURRENT_USER = "current.user"; } </code></pre> <p>I would like to use these constants within a JSP to test for the presence of these attributes, something like:</p> <pre><code>&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; &lt;%@ page import="com.example.Constants" %&gt; &lt;c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}"&gt; &lt;%-- Do somthing --%&gt; &lt;/c:if&gt; </code></pre> <p>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 <code>&lt;c:set&gt;</code>, but again I'm struggling to find the correct syntax.</p> <p><strong>UPDATE:</strong> Further to the suggestion below, I tried:</p> <pre><code>&lt;c:set var="nullUser" scope="session" value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" /&gt; </code></pre> <p>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</p> <pre><code>&lt;c:set var="nullUser" scope="session" value="${sessionScope['current.user'] eq null}" /&gt; &lt;%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %&gt; </code></pre> <p>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.....</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload