tomcat拒绝访问特定文件
问题描述:
我在Tomcat中有一个webapp,其主JSP文件包含页面中心的另一个JSP文件。我想直接拒绝对该文件的访问,并且只允许直接访问主索引页面。tomcat拒绝访问特定文件
此外,我不希望用户能够直接从我的web应用程序获取图像。
我该如何拒绝Tomcat的请求?我想要所有的请求转发到我的主页面。
答
一个办法是实施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
}
答
关于包括JSP文件,你应该把它们
WEB-INF
文件夹下。这样,它们不能直接从浏览器访问,但它允许您的主JSP文件包含它们。与图像相同的东西,但图像有点棘手,但可行。将它们放在
WEB-INF
文件夹下,因此,您无法从<img>
标签静态访问图像。你将需要做的是创建作为代理来获取图像和流出来一个servlet ......所以,你<img>
看起来是这样的: -
====== ====
<img src="/webapp/imageServlet?img=world.jpg">
==========
你那么ImageServlet
将宣读WEB-INF
文件夹world.jpg
文件和流出来的图像。
答
来自页面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>
我怎样才能获得被请求的页面? – shay 2011-03-17 18:37:35