【问题标题】:How to make some pages not directly accessible from browser?如何使某些页面无法从浏览器直接访问?
【发布时间】:2023-03-25 07:25:01
【问题描述】:

例如:我的网络应用程序中有两个文件:1] index.html 2] some.html(或 jsp)

只能从浏览器访问 index.html,

所以如果我调用 localhost:8080/index.html,它应该返回实际页面,并且在加载时如果我直接(重定向)到 some.html,那么应该会显示 some.html 页面,

如果我直接调用localhost:8080/some.html,应该会抛出无法直接访问页面的错误,如果我将webapp托管在tomcat服务器中,有什么方法可以实现吗?

【问题讨论】:

    标签: html jsp tomcat webpage


    【解决方案1】:

    一个常见的解决方案是将它们移动到 WEB-INF 目录下。从这里它们不能公开访问,但您可以将 Servlet 或其他控制器转发给它们

    https://docs.oracle.com/cd/E21764_01/web.1111/e13712/configurewebapp.htm#WBAPP158

    WEB-INF 目录不是公共文档树的一部分 应用。无法提供 WEB-INF 目录中包含的文件 通过容器直接发送给客户端。 但是,内容 WEB-INF 目录对使用 getResource 的 servlet 代码可见 和 ServletContext 上的 getResourceAsStream() 方法调用或 使用 RequestDispatcher 包含/转发

    另一种方法是将它们留在 WEB-INF 之外并在 web.xml 中配置安全约束。例如,如果您在 {webapp-root}/pages 中有它们:

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>JSP Files</web-resource-name>
            <description>No direct access to JSP files</description>
            <url-pattern>/pages/*</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>No direct browser access to JSP files</description>
            <role-name>NobodyHasThisRole</role-name>
        </auth-constraint>
    </security-constraint> 
    

    【讨论】:

      【解决方案2】:

      使用Filters 并拒绝访问jsp's

      public class FilterMyJsp implements Filter{
          public void  doFilter(ServletRequest request, ServletReponse response,                
             FilterChain chain) {
            HttpServletRequest req= (HttpServletRequest) request;
            req.getRequestDispather("HandleError.jsp").forward(request,response);
      }
      }
      

      Web.xml <filter> <filter-name>FilterMyJsp</filter-name> <filter-class>my.FilterMyJsp</filter-class> </filter> <filter-mapping> <filter-name>FilterMyJsp</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>

      URL 模式 * 会将此过滤器应用于每个 jsp。您可以设计HandleError.jsp,并在用户尝试访问其他页面时显示相应的错误消息。

      【讨论】:

        猜你喜欢
        • 2016-02-23
        • 2019-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        相关资源
        最近更新 更多