繁体   English   中英

tomcat拒绝访问特定文件

[英]tomcat deny access to specific files

我在Tomcat中有一个webapp,其主JSP文件包含页面中心的另一个JSP文件。 我想直接拒绝访问该文件,并且只允许直接访问主索引页面。

此外,我不希望用户能够直接从我的webapp获取图像。

我如何用Tomcat拒绝这些请求? 我希望所有请求都转发到我的主页面。

从页面阻止访问包含文件

添加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>

一种方法是实现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>

编辑

您需要知道的有关请求哪个页面的所有内容都在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
}
  1. 关于包含的JSP文件,您应将它们放在WEB-INF文件夹下。 这样,它们不能直接从浏览器访问,但它允许您的主JSP文件包含它们。

  2. 与图像相同,但图像有点棘手,但可行。 将它们放在WEB-INF文件夹下,因此,您无法从<img>标记静态访问图像。 你需要做的是创建一个servlet作为代理来获取图像并将其流出...所以,你的<img>看起来像这样:

==========

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

==========

然后,您的ImageServlet将从WEB-INF文件夹中读取world.jpg文件并将图像流出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM