how to know the path of the webcontainer using java? [duplicate]

百般思念 提交于 2019-12-11 23:23:46

问题


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.


回答1:


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:

  • getResourceAsStream() vs FileInputStream



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/6097814/how-to-know-the-path-of-the-webcontainer-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!