tomcat无法获取ServletContext.getContextPath()

时间:2011-02-22 00:50:30

标签: java tomcat contextpath

我正在尝试获取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>
你可以帮我吗?

2 个答案:

答案 0 :(得分: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">

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

答案 1 :(得分: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()