在Tomcat中可以通过配置web.xml文件和使用Tomcat提供的<security-constraint>和<login-config>元素来实现访问控制。
web.xml文件: 在web.xml文件中添加<security-constraint>元素来定义访问控制规则。可以指定哪些URL模式需要进行访问控制,以及需要哪种角色才能访问。<security-constraint> <web-resource-collection> <web-resource-name>Protected Area</web-resource-name> <url-pattern>/protected/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> <login-config>元素: 在web.xml文件中添加<login-config>元素来指定登录验证方式。<login-config> <auth-method>BASIC</auth-method> <realm-name>Protected Area</realm-name> </login-config> tomcat-users.xml文件中配置用户角色和权限信息。<tomcat-users> <role rolename="admin"/> <user username="admin" password="admin" roles="admin"/> </tomcat-users> 通过以上步骤配置后,访问/protected/*路径时,用户需要输入用户名和密码,并且需要具有admin角色才能访问。