2016-02-27 29 views
0

我正面臨在基於Servlet的Java EE中編寫Web應用程序的問題。一切正常,但我不知道如何正確地將jscss文件附加到我的html頁面。我已經閱讀了關於這個網頁的一些答案和帖子,我不想寫我自己的servlet來做到這一點,因爲據我所知,Tomcat提供了DefaultServlet,它服務於我想要的。現在,我試圖編寫這個類的實現,這裏有:Java EE Tomcat DefaultServlet擴展不適用於靜態文件

package xx.xx.xx; 

import java.io.File; 
import java.io.IOException; 

import javax.servlet.RequestDispatcher; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebInitParam; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletRequestWrapper; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.catalina.servlets.DefaultServlet; 

@WebServlet(urlPatterns={"/js/*","/css/*","/libs/*"}) 
public class StaticContent extends DefaultServlet { 

    public StaticContent() { 
     super(); 
    } 

    private static final long serialVersionUID = 1L; 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     File f = new File(StaticContent.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"../css/global.css"); 
     System.out.println("_____HERE " + request.getRequestURL() + " | " + f.exists()); 
     super.doGet(request, response); 
    } 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     throw new UnsupportedOperationException(); 
    } 

} 

我不明白。它仍然不起作用。 java文件系統識別它,並在file.exists()上返回true,但服務器不。當我嘗試從瀏覽器訪問它時,它也會失敗,其中包括404。任何想法我應該在這裏做什麼?資產文件位於WEB-INFhtml的旁邊。

+0

我想絕對路徑,並realtive有和沒有'/'。沒有一項工作:c – kcdsh

回答

0

確定我得到了這個在這裏工作是我的doGet方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    String arr[] = request.getRequestURL().toString().split("/"); 
    String file = arr[arr.length-1]; 
    String folder = arr[arr.length-2]; 
    request.getRequestDispatcher("/WEB-INF/"+folder+"/"+file).forward(request, response); 
}