tomcat unable to get ServletContext.getContextPath()

shay picture shay · Feb 22, 2011 · Viewed 7.6k times · Source

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

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?

Answer

Sergiy Shyrkov picture Sergiy Shyrkov · Feb 23, 2011

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.