Jasper
Jasper

Reputation: 8705

Java Web-Application: Why is getContextPath empty?

For this URL:
http://localhost:8888/myapp/myservlet/item

In my servlet inside doGet method:

System.out.println("req.getServletPath(): " + req.getServletPath());
System.out.println("req.getRequestURL(): " + req.getRequestURL());
System.out.println("req.getRequestURI(): " + req.getRequestURI());
System.out.println("req.getContextPath(): " + req.getContextPath());
System.out.println("req.getPathInfo(): " + req.getPathInfo());

Console output:

req.getServletPath(): 
req.getRequestURL(): http://localhost:8888/myapp/myservlet/item
req.getRequestURI(): /myapp/myservlet/item
req.getContextPath(): 
req.getPathInfo(): /myapp/myservlet/item

Why is the getContextPath and getServletPath empty?
If it matters this is a (google) web-project in eclipse which gets deployed on jetty.

I am trying to get part of URL that is after the servlet name i.e /item in this case.

Upvotes: 8

Views: 5549

Answers (1)

Pavel Uvarov
Pavel Uvarov

Reputation: 1100

About context path - this path is "subpath" for applications loaded to container. As your contextPath is empty then your application configured in container as default application with no contextPath. It's totally right - in most cases you don't really need any context path. But you should be ready to work with it.

About getServletPath - I'm not sure... But it looks like your app manage your servlet, while getServletPath method asks container (and container don't know anything about your servlet). To control what is managed by container and what by application you can see your web.xml file and read all <servlet> and <servlet-mapping> elements

Upvotes: 3

Related Questions