Reference list of constants from Spring JSP

Our client library contains a couple of Java classes with many constants as static ints:

public class Filter {
    public static final class COMPARATOR {
        public static final int EQUALS = 1;
        public static final int NOTEQUALS = 2;
        ...
    }
}

      

The problem is I want to use these constants in the JSP page. Since this is a Spring project, I am trying to use the Spring eval tag:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<spring:eval var="equals" expression="T(com.model.Filter$COMPARATOR).EQUALS"/>

      

While the above works, I will need to define eval separately for each individual constant, and there could be hundreds of these guys. Is there a way to avoid this? I would like something like this:

<spring:eval var="COMPARATOR" expression="T(com.model.Filter$COMPARATOR)"/>

      

where can i use this syntax: $ {COMPARATOR.EQUALS} (as is, this gives javax.el.PropertyNotFoundException).

+3


source to share


1 answer


TypeLocator

We can omit the fully qualified name if we provide a type locator as shown below:

StandardEvaluationContext context = new StandardEvaluationContext();
context.setTypeLocator(typeName -> {
  try {
    return Class.forName("com.github.zzt93.syncer.util." + typeName);
  } catch (ClassNotFoundException e) {
    throw new IllegalArgumentException(e);
  }
});
Class testClass = parser.parseExpression("T(SpringELTest)").getValue(context, Class.class);
System.out.println(testClass);

      

Runnable example from here .

TLD



However, as far as I know, at the moment the Spring tld does not support a given evaluation context when getting a value.

So we can define our own tags, but use spring el to evaluate:

public class EvalTag extends TagSupport {
  private Object bean;
  private String propertyExpression; //Ex: 'model.sharingTocs'
  private String var;

  @Override
  public int doEndTag() throws JspException {
    try {
      // evaluate it as above code show
    } catch (Exception ex) {
      throw new JspTagException(ex.getMessage(), ex);
    }
    return EVAL_PAGE;
  }
}

      


Hope it helps.

0


source







All Articles