javaee url-pattern “/” matches everything, while t

2019-05-21 10:59发布

问题:

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Common pages</web-resource-name>
      <url-pattern>/test1.html</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>MY_GROUP</role-name>
    </auth-constraint>
  </security-constraint>

as expected, with this constraint, the page /test1.html needs authentication, and the page /test2.html does not need authentication.

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Common pages</web-resource-name>
      <url-pattern>/*</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>MY_GROUP</role-name>
    </auth-constraint>
  </security-constraint>

as expected, with this constraint, all pages need authentication, including /test2.html.

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Common pages</web-resource-name>
      <url-pattern>/</url-pattern>
      <url-pattern>/test1.html</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>MY_GROUP</role-name>
    </auth-constraint>
  </security-constraint>

with this constraint, I would expect that the page /test1.html and / need authentication, but the page /test2.html should not need authentication.

However, it turns out that /test2.html also requires authentication.

Question 1. Is that normal? Why is so?

Question 2. Where is it written in the specification that the url-pattern "/" is equivalent to "/*"? Java Servlet Specification 2.5: http://goo.gl/UxoPL

Question 3. How can I tell that the root page "/" requires authentication, but not the other pages?

ps: I am using jboss-eap-4.3.

回答1:

The / is a special URL pattern which matches everything which is not matched by any of the more specific servlet URL patterns in the same webapp like /app/*, *.do, etc. It's, say, the "default servlet". This is by default handled by the servletcontainer's own default servlet and is usually used for static resources like plain vanilla HTML/CSS/JS/image files for which no one of the webapp's own servlets would be invoked. Tomcat for example has the DefaultServlet for this purpose.

The /* is an overly generic URL pattern which matches everything, including the "default servlet" requests. This URL pattern is normally to be used by filters only, not by servlets. Otherwise you'd have to reinvent the job of servletcontainer's own default servlet to deal with static files like plain vanilla HTML/CSS/JS/image files.

As to your concrete functional requirement, you need to specify a welcome file for /

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

and then put the security constraint URL pattern on /index.html instead.