开发者

tomcat unable to get ServletContext.getContextPath()

I am trying to get the contextPath but I get this exception

ServletContextHandler.contextInitialized()HERE MY PRINT
 2011-02-22 02:45:38,614 ERROR m开发者_如何学运维ain 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

this is my ServletContextListener class

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

}

and this is my 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>

can you help me please?


the ServletContext.getContextPath() is only available from Servlet 2.5 spec. Your web.xml deployment descriptor uses 2.3 DTD, so it forces Servlet 2.3 compatibility. If you are running on Tomcat 6.0.x or later, exchange the DOCTYPE in your web.xml with the 2.5 schema reference:

<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">

Let me know, please, if it solves the problem.


You will need to set store the context path somewhere. For example, you can do something like this:-

public class ServletContextHandler implements ServletContextListener {

  ...

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

  ...
}

In this example, I created MyServletContext that basically contains 2 static methods that allow you to set and get the stored context path:-

public class MyServletContext {
    private static String   contextPath;

    private MyServletContext() {
    }

    public static String getContextPath() {
        return contextPath;
    }

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

}

To get the context path, instead of doing request.getContextPath(), you invoke MyServletContext.getContextPath().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜