简体   繁体   中英

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 ie /item in this case.

I find this graphic from HttpServletRequest Path Decoding useful:

在此处输入图片说明

It looks like the problem is that the application is deployed on the root, and then the servlet has a path that includes the application name. Attach the web.xml file in order to verify this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM