如何在web.xml中配置url映射以限制访问?

Ash*_*wal 5 web.xml servlets

我在以下结构中有几页.

--Project
  |---WebContect
      |----Admin/ *
      |----Author/ * 
      |----Readonly/ * 
      |----Index.jsp
Run Code Online (Sandbox Code Playgroud)

我想限制用户访问Admin,AuthorReadonly.我不希望任何人访问这些页面.如果有人试图这样做,应该重定向到index.jsp.

我想到的最简单的解决方案是使用a Filter,但我试图找到它是否可以使用web.xml.

Bal*_*usC 15

如果您希望没有人能够直接访问这些页面,只需将它们放在/WEB-INF文件夹中即可.

Project
 `-- WebContect
      |-- WEB-INF
      |    |-- Admin
      |    |-- Author
      |    `-- Readonly
      `-- Index.jsp
Run Code Online (Sandbox Code Playgroud)

这样,页面不可公开访问,而只能由执行转发的servlet访问.当最终用户尝试直接访问它时,他将得到的只是HTTP 404错误.

另一种方法是配置无角色<security-constraint>.

<security-constraint>
    <display-name>Restrict direct access to certain folders</display-name>
    <web-resource-collection>
        <web-resource-name>Restricted folders</web-resource-name>
        <url-pattern>/Admin/*</url-pattern>
        <url-pattern>/Author/*</url-pattern>
        <url-pattern>/Readonly/*</url-pattern>
    </web-resource-collection>
    <auth-constraint />
</security-constraint>
Run Code Online (Sandbox Code Playgroud)

当最终用户尝试访问它们时,他将得到的只是HTTP 403错误.

无论哪种方式,都无法以index.jsp这种方式重定向最终用户.只有一个Filter可以做到这一点.您可以index.jsp为404或403 配置错误页面位置

<error-page>
    <error-code>404</error-code>
    <location>/index.jsp</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

但这将涵盖所有 404(或403),不确定这是否是你想要的.