2013-08-28 58 views
0

我使用的是捕獲所有的servlet:[全部的Servlet防止資源加載

@WebServlet(name="RequestHandler", urlPatterns="/*") 
public class RequestHandler extends HttpServlet { 

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    doPost(request, response); 
} 

@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    new SeedPlanter(request, response).sow(); 
} 

} 

要處理所有的請求。請注意0​​/ *。這是因爲它加載了各種各樣的東西,比如模板,處理對象等等。servlet基本上只是一個門面,它位於處理所有html渲染的自定義框架之前。

問題是我不能再直接訪問資源。

例如,如果我想加載一個在web-inf目錄之外的HTML文件(localhost:8080/myapp/test.html),它會給我一個404錯誤。事實上,即使我嘗試在頁面上加載圖像(localhost:8080/myapp/images/test.png),它也會提供404資源未找到。刪除servlet顯然會破壞整個應用程序,但它確實允許我加載這些資源,所以我確信它的servlet導致了問題。

如何使用像我這樣的servlet,但也能夠加載這些資源?

回答

0

我最終使用了一個單獨的servlet來監聽我的圖像,css,js文件夾(您可以根據需要添加儘可能多的urlPatterns)。

@WebServlet(name="CommonRequestHandler", urlPatterns={"/images/*", "/css/*"}) 
public class CommonRequestHandler extends HttpServlet { 

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    doPost(request, response); 
} 

@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    ServletContext context = getServletContext(); 
    String path = request.getRequestURI().substring(request.getContextPath().length()+1, request.getRequestURI().length()); 
    String fileName = context.getRealPath(path); 

    //Get MIME type 
    String mimeType = context.getMimeType(fileName); 
    if(mimeType == null) { 
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     return; 
    } 

    //Set content type 
    response.setContentType(mimeType); 

    //Set content size 
    File file = new File(fileName); 
    response.setContentLength((int) file.length()); 

    //Open file and output streams 
    FileInputStream in = new FileInputStream(file); 
    OutputStream out = response.getOutputStream(); 

    //Copy file content to output stream 
    byte[] buf = new byte[1024]; 
    int count = 0; 
    while((count = in.read(buf)) >= 0) { 
     out.write(buf, 0, count); 
    } 
    in.close(); 
    out.close(); 
} 
} 

該代碼只是找到該文件並返回字節回瀏覽器。

參考:http://java-espresso.blogspot.com/2011/09/webxml-problem-and-solution-for-url.html

0

我想你需要使用Servlet 過濾器在這種情況下,不是Servlets。 Servlet過濾器是一種添加任何圍繞請求流的代碼的方法。互聯網上有很多例子,這裏是one of them

0

您可能想要創建/使用servlet過濾器來正確重寫路徑。看起來可能有幫助的There's a good example of one here complete with source code

我已經包含以下內容以供參考,因爲描述符的實際功能經常被錯誤解釋爲應該如何實際執行。映象的

SRV.11.2規格

在theWeb應用程序部署描述,下面的語法用於定義映射:

  • 以/字符開始並且以結束的字符串/ *後綴是用於路徑映射的 。
  • 以*開頭的字符串。前綴被用作擴展映射。
  • 只包含/字符的字符串表示應用程序的「默認」servlet。在這種情況下,servlet路徑是 請求URI減去上下文路徑,路徑信息爲空。

所有其他字符串僅用於精確匹配。