how to know the path of the webcontainer using jav

2019-08-17 11:09发布

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条回答
我命由我不由天
2楼-- · 2019-08-17 11:34

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

查看更多
姐就是有狂的资本
3楼-- · 2019-08-17 11:36

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.

查看更多
虎瘦雄心在
4楼-- · 2019-08-17 11:44

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:

查看更多
登录 后发表回答