Expose Java5 Enum to JSP(JSTL)

July 28, 2008 at 8:46 pm | Posted in Uncategorized | Leave a comment

Currently, Enum cannot be directly referenced in JSTL

We cannot do these:

  • ${ my.package.Enum }
  • ${ someEnum == MyEnum }

So, in order to access enums easily, Enums need to be in HttpServletRequest (request scope) or ServletContext(application scope).

  1. Store in ServletContext (Application scope)
  2. Store in HttpServletRequest (request scope, request.setAttribute())
    • ServletFilter (servlet)
    • HandlerInterceptor (spring)
    • Controller (spring, web-layer-action)

Sample Enum Class

public enum Language {

    private String name;

    Language(String name) {
        this.name = name;

    public String getName() {
        return name;


public class EnumExposureHandlerInterceptor extends HandlerInterceptorAdapter {

    private Set<Class<? extends Enum>> enumClasses = new HashSet<Class<? extends Enum>>();

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        for (Class<? extends Enum> enumClass : enumClasses) {
            final String enumClassName = enumClass.getSimpleName();  // class of enum : Language
            final Enum[] enums = enumClass.getEnumConstants();  // enum instances : EN, JP,...

            // put them into map, so that we can access like this : Language.EN, Language.JP ...
            Map<String, Enum> map = new HashMap<String, Enum>(enums.length);
            for (Enum anEnum : enums) {
                map.put(anEnum.name(), anEnum);

            // seting to scope
            request.setAttribute(enumClassName, map);


    public void setEnumClasses(Set<Class<? extends Enum>> enumClasses) {
        this.enumClasses = enumClasses;

Spring Configuration

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap" ref="urlMap"/>
<property name="interceptors">
            <bean class="mypackage.EnumExposureHandlerInterceptor">
<property name="enumClasses">

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: