Java constants in JSP

41,760

Solution 1

On application startup, you can add the Constants class to the servletContext and then access it in any jsp page

servletContext.setAttribute("Constants", com.example.Constants);

and then access it in a jsp page

<c:out value="${Constants.ATTR_CURRENT_USER}"/>

(you might have to create getters for each constant)

Solution 2

Turns out there's another tag library that provides the same functionality. It also works for Enum constants.

Solution 3

Looks like a duplicate of accessing constants in JSP (without scriptlet)

My answer was:

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.

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:

${bean.manager_role}

Full code at https://rogerkeays.com/access-java-static-methods-and-constants-from-el

Share:
41,760
Dónal
Author by

Dónal

I earn a living by editing text files. I can be contacted at: [email protected] You can find out about all the different kinds of text files I've edited at: My StackOverflow Careers profile

Updated on February 27, 2021

Comments

  • Dónal
    Dónal over 3 years

    I have a class that defines the names of various constants, e.g.

    class Constants {
        public static final String ATTR_CURRENT_USER = "current.user";
    }
    

    I would like to use these constants within a JSP without using Scriptlet code such as:

    <%@ page import="com.example.Constants" %>
    <%= Constants.ATTR_CURRENT_USER %>
    

    There appears to be a tag in the Apache unstandard taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?

    Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?

    Cheers, Don

  • Dónal
    Dónal almost 16 years
    If you could rewrite this without using Scriptlet, you will have answered my question.
  • Dónal
    Dónal almost 16 years
    I really want to avoid creating getters for each constant
  • nhthai
    nhthai almost 9 years
    The setAttribute of servletContext function receive Object as value parameter. Are you sure we can transfer com.example.Constants?
  • Vasil Valchev
    Vasil Valchev over 7 years
    where is "application startup"?