2011-03-17 110 views
6

我在Tomcat中有一個webapp,其主JSP文件包含頁面中心的另一個JSP文件。我想直接拒絕對該文件的訪問,並且只允許直接訪問主索引頁面。tomcat拒絕訪問特定文件

此外,我不希望用戶能夠直接從我的web應用程序獲取圖像。

我該如何拒絕Tomcat的請求?我想要所有的請求轉發到我的主頁面。

回答

4

一個辦法是實施Filter

例如:

package package; 

import javax.servlet.*; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class FilterImplementation implements Filter 
{ 
    public void init(FilterConfig filterConfig) throws ServletException {...} 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
    { 
     // if you detect an illegal request, throw an exception or return without calling chain.doFilter. 
     chain.doFilter(request, response);  
    } 

    public void destroy() {...} 
} 

以下內容添加到web.xml中:

<filter> 
    <filter-name>MyFilter</filter-name> 
    <filter-class>package.FilterImplementation</filter-class> 
</filter> 

<filter-mapping> 
    <filter-name>MyFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

編輯

你的一切需要知道whi ch頁面正在請求的是request參數。參數類型爲ServletRequest但它幾乎總是一個HttpServletRequest這樣你就可以做到以下幾點:

if (request instanceof HttpServletRequest) 
{ 
    HttpServletRequest hrequest = (HttpServletRequest) request; 
    String uri = hrequest.getRequestURI(); // you should be able to just use this 
    String uri = hrequest.getRequestURL(); // otherwise there are more in-depth fields 
} 
+0

我怎樣才能獲得被請求的頁面? – shay 2011-03-17 18:37:35

3
  1. 關於包括JSP文件,你應該把它們WEB-INF文件夾下。這樣,它們不能直接從瀏覽器訪問,但它允許您的主JSP文件包含它們。

  2. 與圖像相同的東西,但圖像有點棘手,但可行。將它們放在WEB-INF文件夾下,因此,您無法從<img>標籤靜態訪問圖像。你將需要做的是創建作爲代理來獲取圖像和流出來一個servlet ......所以,你<img>看起來是這樣的: -

====== ====

<img src="/webapp/imageServlet?img=world.jpg"> 

==========

你那麼ImageServlet將宣讀WEB-INF文件夾world.jpg文件和流出來的圖像。

9

來自頁面Prevent access to include files

添加在web.xml:

<security-constraint> 
    <web-resource-collection> 
     <web-resource-name>Include files</web-resource-name> 
     <description>No direct access to include files.</description> 
     <url-pattern>/inc/*</url-pattern> 
     <http-method>POST</http-method> 
     <http-method>GET</http-method> 
    </web-resource-collection> 
    <auth-constraint> 
     <description>No direct browser access to include files.</description> 
     <role-name>NobodyHasThisRole</role-name> 
    </auth-constraint> 
</security-constraint>