Issue
The Method request.getRequestURI() returns URI with context path.
For example, if the base URL of an application is http://localhost:8080/myapp/
(i.e. the context path is myapp), and I call request.getRequestURI()
for http://localhost:8080/myapp/secure/users
, it will return /myapp/secure/users
.
Is there any way we can get only this part /secure/users
, i.e. the URI without context path?
Solution
If you're inside a front contoller servlet which is mapped on a prefix pattern such as /foo/*
, then you can just use HttpServletRequest#getPathInfo()
.
String pathInfo = request.getPathInfo();
// ...
Assuming that the servlet in your example is mapped on /secure/*
, then this will return /users
which would be the information of sole interest inside a typical front controller servlet.
If the servlet is however mapped on a suffix pattern such as *.foo
(your URL examples however does not indicate that this is the case), or when you're actually inside a filter (when the to-be-invoked servlet is not necessarily determined yet, so getPathInfo()
could return null
), then your best bet is to substring the request URI yourself based on the context path's length using the usual String
method:
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
// ...
Answered By - BalusC
Answer Checked By - Marie Seifert (JavaFixing Admin)