在某些Web应用场景,当我们点击某些链接时,会跳出类似登录操作系统的输入框,要求输入用户名和密码,这是怎么做到的呢?这里以Tomcat服务器为例来实现,其他的服务器包括IIS等都提供类似的功能。
打开Web项目的web.xml,加入以下配置段:
<security-constraint>
<display-name>Security For Basic Login</display-name>
<web-resource-collection>
<web-resource-name>BasicLogin</web-resource-name>
<description>Map to Basic Login Page</description>
<url-pattern>/sec/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>no description</description>
<role-name>tomcat</role-name>
</auth-constraint>
<user-data-constraint>
<description>no description</description>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name></realm-name>
</login-config>
</login-config>
加入这段话后,访问这个应用的sec目录下的的文件时,都会要求输入tomcat已配置的用户名和密码,这在conf目录下的users.xml文件中可以配置