Home ยป accessing constants in JSP (without scriptlet) [duplicate]

accessing constants in JSP (without scriptlet) [duplicate]


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>
<%=Constants.ATTR_CURRENT_USER%> <br />

<%-- 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>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<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'.

<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
<hr />

This outputs:

Using scriptlets





Using JSTL






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 --%> 

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.

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 here is a key you used putting map into Context ย ย ๐Ÿ™‚

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 */ }

Related Solutions

When should I not kill -9 a process?

Generally, you should use kill (short for kill -s TERM, or on most systems kill -15) before kill -9 (kill -s KILL) to give the target process a chance to clean up after itself. (Processes can't catch or ignore SIGKILL, but they can and often do catch SIGTERM.)...

Default value for UUID column in Postgres

tl;dr Call DEFAULT when defining a column to invoke one of the OSSP uuid functions. The Postgres server will automatically invoke the function every time a row is inserted. CREATE TABLE tbl ( pkey UUID NOT NULL DEFAULT uuid_generate_v1() , CONSTRAINT pkey_tbl...

comparing five integers with if , else if statement

try this : int main () { int n1, n2, n3, n4, n5, biggest,smallest; cout << "Enter the five numbers: "; cin >> n1 >> n2 >> n3 >> n4 >> n5 ; smallest=biggest=n1; if(n2>biggest){ biggest=n2; } if(n2<smallest){ smallest=n2;...

How to play YouTube audio in background/minimised?

Here's a solution using entirely free and open source software. The basic idea is that although YouTube can't play clips in the background, VLC for Android can play clips in the background, so all we need to do is pipe the clip to VLC where we can listen to it...

Why not use “which”? What to use then?

Here is all you never thought you would ever not want to know about it: Summary To get the pathname of an executable in a Bourne-like shell script (there are a few caveats; see below): ls=$(command -v ls) To find out if a given command exists: if command -v...

Split string into Array of Arrays [closed]

If I got correct what you want to receive as a result, then this code would make what you want: extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: self.count, by: size).map { Array(self[$0 ..< Swift.min($0 + size,...

Retrieving n rows per group

Let's start with the basic scenario. If I want to get some number of rows out of a table, I have two main options: ranking functions; or TOP. First, let's consider the whole set from Production.TransactionHistory for a particular ProductID: SELECT...

Don’t understand how my mum’s Gmail account was hacked

IMPORTANT: this is based on data I got from your link, but the server might implement some protection. For example, once it has sent its "silver bullet" against a victim, it might answer with a faked "silver bullet" to the same request, so that anyone...

What is /storage/emulated/0/?

/storage/emulated/0/Download is the actual path to the files. /sdcard/Download is a symlink to the actual path of /storage/emulated/0/Download However, the actual files are located in the filesystem in /data/media, which is then mounted to /storage/emulated/0...

How can I pass a command line argument into a shell script?

The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The...

What is pointer to string in C?

argv is an array of pointers pointing to zero terminated c-strings. I painted the following pretty picture to help you visualize something about the pointers. And here is a code example that shows you how an operating system would pass arguments to your...

How do mobile carriers know video resolution over HTTPS connections?

This is an active area of research. I happen to have done some work in this area, so I'll share what I can about the basic idea (this work was with industry partners and I can't share the secret details ๐Ÿ™‚ ). The tl;dr is that it's often possible to identify an...

How do I change the name of my Android device?

To change the hostname (device name) you have to use the terminal (as root): For Eclair (2.1): echo MYNAME > /proc/sys/kernel/hostname For Froyo (2.2): (works also on most 2.3) setprop net.hostname MYNAME Then restart your wi-fi. To see the change, type...

How does reverse SSH tunneling work?

I love explaining this kind of thing through visualization. ๐Ÿ™‚ Think of your SSH connections as tubes. Big tubes. Normally, you'll reach through these tubes to run a shell on a remote computer. The shell runs in a virtual terminal (tty). But you know this part...

Difference between database vs user vs schema

In Oracle, users and schemas are essentially the same thing. You can consider that a user is the account you use to connect to a database, and a schema is the set of objects (tables, views, etc.) that belong to that account. See this post on Stack Overflow:...

What’s the output of this code written in java?

//if you're using Eclipse, press ctrl-shift-f to "beautify" your code and make it easier to read int arr[] = new int[3]; //create a new array containing 3 elements for (int i = 0; i < 3; i++) { arr[i] = i;//assign each successive value of i to an entry in...