ExpEval.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package commons.web.mvc;
  2. import jakarta.servlet.jsp.JspException;
  3. import jakarta.servlet.jsp.PageContext;
  4. import jakarta.servlet.jsp.tagext.Tag;
  5. public class ExpEval {
  6. public static Object evalObject(String attrName, String attrValue, Tag tagObject, PageContext pageContext) throws JspException {
  7. return evalExpression(attrName, attrValue, Object.class, tagObject, pageContext);
  8. }
  9. public static String evalString(String attrName, String attrValue, Tag tagObject, PageContext pageContext) throws JspException {
  10. return (String) evalExpression(attrName, attrValue, String.class, tagObject, pageContext);
  11. }
  12. public static Integer evalInteger(String attrName, String attrValue, Tag tagObject, PageContext pageContext) throws JspException {
  13. return (Integer) evalExpression(attrName, attrValue, Integer.class, tagObject, pageContext);
  14. }
  15. public static Boolean evalBoolean(String attrName, String attrValue, Tag tagObject, PageContext pageContext) throws JspException {
  16. return (Boolean) evalExpression(attrName, attrValue, Boolean.class, tagObject, pageContext);
  17. }
  18. private static Object evalExpression(String attrName, String attrValue, Class<?> expectedType, Tag tagObject, PageContext pageContext) throws JspException {
  19. if (attrValue == null) return null;
  20. if (attrValue.indexOf("${") == -1) {
  21. return attrValue;
  22. }
  23. try {
  24. jakarta.el.ELProcessor elProcessor = new jakarta.el.ELProcessor();
  25. elProcessor.defineBean("pageContext", pageContext);
  26. elProcessor.defineBean("param", pageContext.getRequest().getParameterMap());
  27. return elProcessor.eval(attrValue);
  28. } catch (Exception e) {
  29. throw new JspException("Error evaluating expression: " + attrValue, e);
  30. }
  31. }
  32. }