In a previous question, I learned how to provide my JSP (running on Tomcat 8.0.9) access to static fields and methods of java.lang classes or even, for example, classes in the java.time
package using code like this:
package test;
import javax.el.ELContextEvent;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.jsp.JspFactory;
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
JspFactory.getDefaultFactory().getJspApplicationContext(event.getServletContext()).addELContextListener((ELContextEvent e) -> {
e.getELContext().getImportHandler().importPackage("java.time");
});
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
And now I can do: ${LocalDate.now{}}
from within my JSP. However, when I attempt to import my own class into the el context:
@Override
public void contextInitialized(ServletContextEvent event) {
JspFactory.getDefaultFactory().getJspApplicationContext(event.getServletContext()).addELContextListener((ELContextEvent e) -> {
e.getELContext().getImportHandler().importPackage("java.time");
e.getELContext().getImportHandler().importClass("test.LocalDateUtils");
});
}
Given the test.LocalDateUtils class:
package test;
import java.time.LocalDate;
public final class LocalDateUtils {
public static boolean isToday(LocalDate date) {
return LocalDate.now().equals(date);
}
}
When invoked from the JSP using:
${LocalDateUtils.isToday(LocalDate.now())}
I run into the exception:
javax.el.ELException: The class [test.LocalDateUtils] could not be imported as it could not be found
javax.el.ImportHandler.importClass(ImportHandler.java:114)
How do I add my custom classes into the ImportHandler's classpath so that they can be found and resolved?