This question already has answers here:
What does servletcontext.getRealPath(“/”) mean and when should I use it
(4个答案)
2年前关闭。
有人可以为此提供替代方案吗?
如果您还显示了一些示例代码,那将非常有帮助。
但是,ServletContext.getRealPath(String path)的API文档指出:
因此,API正在履行其契约(Contract)!但是,一切都不会丢失,因为您可以使用ServletContext中定义的以下方法从WAR加载资源:
(4个答案)
2年前关闭。
getRealPath()
返回本地系统中的实际路径,但与.war
文件一起部署时返回null。<%@ page import="java.io.*" %>
<%@ page contentType="text/html;charset=ISO-8859-1" %>
<%
int iLf = 10;
char cLf = (char)iLf;
String a= application.getResource("/");
//String myfile = application.getRealPath("/")+ "generate.xml";
//String myfile = request.getContextPath()+"generate.xml";
//String myfile = request.getRealPath("/")+"generate.xml";
out.println(myfile);
File outputFile = new File(myfile);
outputFile.createNewFile();
FileWriter outfile = new FileWriter(outputFile);
outfile.write(" <?xml version='1.0' encoding='UTF-8'?> "+cLf);
outfile.write(" <playlist version='1' xmlns = 'http://xspf.org/ns/0/' > " +cLf);
outfile.write(" <title>My Band Rocks Your Socks</title> "+cLf);
outfile.write("<trackList>"+cLf);
%>
<%! String[] sports; %>
<%
sports = request.getParameterValues("sports");
out.println("<html><body><h1>hello</h1></body></html>");
if (sports != null)
{
for (int i = 0; i < sports.length; i++)
{
// outfile.writeln (sports[i]);
String total=sports[i];
String[] sa=total.split("[,]");
// String[] sub=new String();
outfile.write("<track>"+cLf);
for (int j=0;j<sa.length;j++)
{
// outfile.writeln(sa[j]);
// outfile.writeln("sa["+j+"]="+sa[j]);
if( j == 0)
{
outfile.write("<location>" + sa[0] +"</location>"+cLf);
}
else if (j == 1)
{
outfile.write("<image>" + sa[1] +"</image>"+cLf);
}
else if( j==2)
{
outfile.write("<title>" + sa[2] +"</title>"+cLf);
}
}// end of inner for loop()
outfile.write("</track>"+cLf);
//outfile.writeln();
}// end of outer for()
}
//else outfile.writeln ("<b>none<b>");
outfile.write(" </trackList> "+cLf);
outfile.write(" </playlist> "+cLf);
outfile.close();
%>
<object type="application/x-shockwave-flash" width="400" height="170"
data="xspf_player.swf?playlist_url=generate.xml">
<param name="movie" value="xspf_player.swf?playlist_url=generate.xml" />
</object>
有人可以为此提供替代方案吗?
如果您还显示了一些示例代码,那将非常有帮助。
最佳答案
首先,不建议使用ServletRequest.getRealPath(String path)。适当的替换是:
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath(request.getContextPath());
但是,ServletContext.getRealPath(String path)的API文档指出:
因此,API正在履行其契约(Contract)!但是,一切都不会丢失,因为您可以使用ServletContext中定义的以下方法从WAR加载资源:
ServletContext context = session.getServletContext();
InputStream is = context.getResourceAsStream("generate.xml");
07-26 00:57