我有一個具有平面文件(或稱爲文本文件)的動態Web項目。我創建了一個我需要使用這個文件的servlet。如何獲取j2ee項目中資源的相對路徑
我的代碼如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// String resource = request.getParameter ("json") ;
if (resource != null && !resource.equals ("") ) {
//use getResourceAsStream () to properly get the file.
InputStream is = getServletContext().getResourceAsStream ("rateJSON") ;
if (is != null) { // the resource exists
response.setContentType("application/json");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
StringWriter sw = new StringWriter () ;
for (int c = is.read () ; c != -1; c = is.read () ) {
sw.write (c) ;
}
PrintWriter out = response.getWriter();
out.print (sw.toString()) ;
out.flush();
}
}
}
的問題是,InputStream爲具有空值。
我不知道如何得到正確的相對路徑。 我使用JBOSS作爲應用服務器。
我在Dynamic Web Project的WebContent目錄中添加了資源文件。 作爲不同的計算策略,我嘗試這樣做:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletConfig config = getServletConfig();
String contextName = config.getInitParameter("ApplicationName");
System.out.println("context name"+ contextName);
String contextPath = config.getServletContext().getRealPath(contextName);
System.out.println("context Path"+contextPath);
//contextPath = contextPath.substring(0, contextPath.indexOf(contextName));
contextPath += "\\rateJSON.txt";
System.out.println(contextPath);
String resource = request.getParameter ("json") ;
System.out.println("Hi there1"+resource);
if (resource != null && !resource.equals ("") ) {
System.out.println("Hi there");
//use getResourceAsStream () to properly get the file.
//InputStream is = getServletContext().getResourceAsStream (resource) ;
InputStream is = getServletConfig().getServletContext().getResourceAsStream(contextPath);
if (is != null) { // the resource exists
System.out.println("Hi there2");
response.setContentType("application/json");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
StringWriter sw = new StringWriter ();
for (int c = is.read () ; c != -1; c = is.read () ) {
sw.write (c) ;
System.out.println(c);
}
PrintWriter out = response.getWriter();
out.print (sw.toString()) ;
System.out.println(sw.toString());
out.flush();
}
}
}
contextPath的值現在:C:\ JBOSS \ jboss-5.0.1.GA \服務器\默認\ TMP \ 4p72206b-uo5r7k-g0vn9pof-1 -g0vsh0o9-b7 \ Nationwide.war \ WEB-INF \ rateJSON
但是在這個位置rateJSON文件不存在嗎?看來JBOSS不是把這個文件放在App.war中還是不部署它? 有人可以幫我嗎?
在Nationwide.war中,「rateJSON」文件不存在。爲什麼?? – Neeraj 2009-10-17 04:23:27
由於某些原因,無論打包的WAR是否包含該文件。您是使用Ant腳本構建WAR還是自動將其部署到IDE中的服務器? – 2009-10-17 06:20:21
自動部署到服務器 – Neeraj 2009-10-17 17:37:14