定義角色
tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?><!-- 不建議這樣做,如果不重啓就無法修改內容 -->
<tomcat-users>
<role rolename="Guest"/>
<role rolename="Member"/>
<role rolename="Admin" />
<user username="Bill" password="coder" roles="Admin, Member, Guest"/>
<user username="Bill" password="coder" roles="Member, Guest"/>
<user username="Bill" password="coder" roles="Guest"/>
</tomcat-users>
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 定義角色 -->
<security-role><role-name>Admin</role-name></security-role>
<security-role><role-name>Member</role-name></security-role>
<security-role><role-name>Guest</role-name></security-role>
<!-- 定義資源/方法約束 -->
<security-constraint>
<web-resource-collection>
<web-resource-name>UpdateRecipes</web-resource-name> <!-- 必要,由工具使用 -->
<url-pattern>/Beer/AddRecipe/*</url-pattern>
<url-pattern>/Beer/ReviewRecipe/*</url-pattern>
<http-method>GET</http-method> <!-- 未指定時全部HTTP方法都受約束 -->
<http-method>POST</http-method>
</web-resource-collection>
<!-- 列出能調用受約束HTTP方法的角色 -->
<auth-constraint>
<role-name>Admin</role-name>
<role-name>Member</role-name>
</auth-constraint>
<!-- 以聲明方式保守地實現數據機密性和完整性 -->
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
<!--
NONE 默認值,沒有數據保護
INTEGRAL 數據在傳輸過程中不能更改
CONFIDENTIAL 數據在傳輸過程中不能被別人看到
-->
</security-constraint>
<!-- 啓用認證 -->
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<!--
BASIC 聲明瞭這個元素,餘下的一切都將由容器負責,請求一個受限資源時,容器會自動詢問用戶名和口令
DIGEST 摘要認證,如果容器支持,它會處理所有細節
CLIENT-CERT 客戶證書認證,這種認證能提供最大強度的保護,但是客戶必須先有證書
FORM 表單認證,如果啓用<login-config>要如下寫法
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/loginPage.html</form-login-page>
<form-error-page>/loginError.html</form-error-page>
</form-login-config>
</login-config>
-->
</web-app>
基於表單的認證
loginPage.html
<body>
Please login daddy-o
<!-- HTML登錄表單中有3項是與容器通信的關鍵j_security_check,j_username,j_password -->
<!-- 要讓容器工作HTML的登錄表單的action必須是j_security_check -->
<form action="j_security_check" method="POST">
<input type="text" name="j_username">
<!-- 容器要求HTTP請求把用戶名存儲在j_username中 -->
<input type ="password" name="j_password">
<input type="submit" value="Enter">
</form>
</body>