I need to get the web container path using java, is there any method for that? I need to use it using JSP or Servlet to get a file path.
3 Answers
I need to use it using JSP or Servlet to get a file path.
So the file is stored in the public webcontent of the WAR? Use ServletContext#getRealPath()
.
String relativeWebPath = "/file.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file); // I guess this is what you want.
// ...
Note that this only works when the WAR is expanded by the container. Otherwise better use ServletContext#getResourceAsStream()
if all you really want is to get an InputStream
of it.
String relativeWebPath = "/file.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
See also:
You're probably looking for HttpServletRequest#getContextPath()
:
Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.
...or getServletPath()
:
Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.

- 354,903
- 100
- 647
- 710
You're interested in getContextPath()
method of HttpServletRequest
.

- 42,730
- 18
- 77
- 103