tomcat配置文件web.xml中</web-app>前加入以下内容

<security-constraint>  

  <display-name>Example Security Constraint</display-name>
  <web-resource-collection>  
      <web-resource-name>My Test</web-resource-name>  
      <url-pattern>/test/*</url-pattern>  
      <http-method>DELETE</http-method>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
      <http-method>PUT</http-method>
  </web-resource-collection>
  <auth-constraint>
    <role-name>role1</role-name>  
  </auth-constraint>  
</security-constraint>  
<login-config>  
    <auth-method>BASIC</auth-method>  
    <realm-name>My Test</realm-name>  
</login-config>
 
 
然后在tomcat-users.xml中添加相关权限的账号密码
<role rolename="role1"/>
<user username="role1" password="tomcat" roles="role1"/>
 
重启tomcat之后访问http://IP/test就会弹出提示框需要输入账号密码了