0

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Maverick
  • 2,738
  • 24
  • 91
  • 157

3 Answers3

2

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

You're interested in getContextPath() method of HttpServletRequest.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103