当前位置: 技术问答>java相关
请问:如何得到jsp所在的物理路径和web虚拟路径?
来源: 互联网 发布时间:2014-12-22
本文导语: | You should use the ServletContext.getRealPath method to access files in your context. In JSP, the ServletContext is exposed through the implicit object "application". For example: new File(application.getRealPath("/WEB-INF/") + "mydatafile.txt");...
|
You should use the ServletContext.getRealPath method
to access files in your context.
In JSP, the ServletContext is exposed through the implicit object
"application". For example:
new File(application.getRealPath("/WEB-INF/") + "mydatafile.txt");
or
new File(application.getRealPath("/WEB-INF/mydatafile.txt");
As you notice the File parameter is given in the form of a URL
that starts off with "/". The file URL is relative to your
Servlet Context although it starts off with "/".
The above getRealPath call from a Servlet may look like:
new File(getServletContext().getRealPath("/WEB-INF/") + "mydatafile.txt");
or
new File(getServletContext().getRealPath("/WEB-INF/mydatafile.txt");
Another method to use to access Files is ServletContext.getResourceAsStream.
ServletContext.getResourceAsStream is used in the follwing manner:
String text = null;
InputStream mi = application.getResourceAsStream("/WEB-INF/data.txt");
int av = mi.available();
if (av > 0)
{
byte[] b = new byte[av];
mi.read(b,0,av);
text = new String (b);
}
to access files in your context.
In JSP, the ServletContext is exposed through the implicit object
"application". For example:
new File(application.getRealPath("/WEB-INF/") + "mydatafile.txt");
or
new File(application.getRealPath("/WEB-INF/mydatafile.txt");
As you notice the File parameter is given in the form of a URL
that starts off with "/". The file URL is relative to your
Servlet Context although it starts off with "/".
The above getRealPath call from a Servlet may look like:
new File(getServletContext().getRealPath("/WEB-INF/") + "mydatafile.txt");
or
new File(getServletContext().getRealPath("/WEB-INF/mydatafile.txt");
Another method to use to access Files is ServletContext.getResourceAsStream.
ServletContext.getResourceAsStream is used in the follwing manner:
String text = null;
InputStream mi = application.getResourceAsStream("/WEB-INF/data.txt");
int av = mi.available();
if (av > 0)
{
byte[] b = new byte[av];
mi.read(b,0,av);
text = new String (b);
}