2

上一个问题中,我学习了如何让我的 JSP(在 Tomcat 8.0.9 上运行)访问 java.lang 类的静态字段和方法,甚至,例如,java.time使用如下代码的包中的类:

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) {}
}

现在我可以做到:${LocalDate.now{}}在我的 JSP 中。但是,当我尝试将自己的类导入 el 上下文时:

@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");
  });
}

给定 test.LocalDateUtils 类:

package test;

import java.time.LocalDate;

public final class LocalDateUtils {

  public static boolean isToday(LocalDate date) {
    return LocalDate.now().equals(date);
  }
}

从 JSP 调用时使用:

${LocalDateUtils.isToday(LocalDate.now())}

我遇到了异常:

javax.el.ELException: The class [test.LocalDateUtils] could not be imported as it could not be found
javax.el.ImportHandler.importClass(ImportHandler.java:114)

如何将我的自定义类添加到 ImportHandler 的类路径中,以便可以找到并解决它们?

4

0 回答 0