1

我正在尝试获取 contextPath 但我得到了这个异常

ServletContextHandler.contextInitialized()HERE MY PRINT
 2011-02-22 02:45:38,614 ERROR main tomcat.localhost./photo.Context - Error listenerStart
 2011-02-22 02:45:38,615 ERROR main tomcat.localhost./photo.Context - Context startup failed due to previous errors

这是我的ServletContextListener

public class ServletContextHandler implements ServletContextListener {
  private final static Logger logger = Logger.getLogger(ServletContextHandler.class);

  public ServletContextHandler(){}

  public void contextInitialized(ServletContextEvent contextEvent){
    try{
    //LOG DEBUG
    logger.debug("Server.init()-> set context path");
    System.out.println("ServletContextHandler.contextInitialized()HERE MY PRINT");
    System.out.println("ServletContextHandler.contextInitialized() " + contextEvent.getServletContext().getContextPath());
    }catch(Exception e){
      e.printStackTrace();
    }
  }

  public void contextDestroyed(ServletContextEvent contextEvent){
  }

}

这是我的 web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>
     <listener>
        <listener-class>
            utils.ServletContextHandler
        </listener-class>
    </listener>
</web-app>

你能帮我吗?

4

2 回答 2

1

ServletContext.getContextPath() 仅适用于 Servlet 2.5 规范。您的 web.xml 部署描述符使用 2.3 DTD,因此它强制 Servlet 2.3 兼容。如果您在 Tomcat 6.0.x 或更高版本上运行,请将 web.xml 中的 DOCTYPE 与 2.5 架构参考交换:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

请告诉我,如果它解决了问题。

于 2011-02-23T15:25:11.170 回答
0

您将需要在某处设置存储上下文路径。例如,您可以执行以下操作:-

public class ServletContextHandler implements ServletContextListener {

  ...

  public void contextInitialized(ServletContextEvent contextEvent){
     MyServletContext.setContextPath(contextEvent.getServletContext().getContextPath());
  }

  ...
}

在此示例中,我创建MyServletContext的基本上包含 2 个静态方法,允许您设置和获取存储的上下文路径:-

public class MyServletContext {
    private static String   contextPath;

    private MyServletContext() {
    }

    public static String getContextPath() {
        return contextPath;
    }

    public static void setContextPath(String cp) {
        contextPath = cp;
    }

}

要获取上下文路径,request.getContextPath()请调用MyServletContext.getContextPath().

于 2011-02-22T03:18:33.723 回答