安全域
Web资源的设置
需要在web.xml文件中加入<security-constraint>、<login-config>、<security-role>元素。
例如在Tomcat的admin应用中的配置:
< display-name > Tomcat Server Configuration Security Constraint </ display-name >
< web-resource-collection >
< web-resource > Protected Area </ web-resource >
< url-pattern > *.htm </ url-pattern >
< url-pattern > *.jsp </ url-pattern >
< url-pattern > *.do </ url-pattern >
</ web-resource-collection >
< auth-constraint >
< role-name > admin </ role-name >
</ auth-constraint >
</ security-constraint >

上面的代码表明:只有admin角色才能访问admin应用中的*.jsp、*.do和*.html资源。
另一个例子是jsp-examples应用:
< display-name > Tomcat Server Configuration Security Constraint </ display-name >
< web-resource-collection >
< web-resource > Protected Area </ web-resource >
< url-pattern > /security/protected/* </ url-pattern >
< http-method > DELETE </ http-method >



</ web-resource-collection >
< auth-constraint >
< role-name > tomcat </ role-name >


</ security-constraint >

上面的代码表明:只要tomcat和role1角色才可以以DELETE、GET、POST和GET方式访问jsp-exzmples应用URL为/security/protected/下的资源。
在web.xml中加入<login-config>元素-系统会以对话框的方式进行登陆
< auth-method > FORM </ auth-method >


< from-login-page > /login/login.jsp </ from-login-page >


</ login-config >

<auth-method>有三个可选项:BASIC、DIGEST、FORM。
BASIC-基本验证:访问受保护资源时,会弹出一对话框。要求输入用户名和密码,如果连续3次失败后,会显示一个错误页面。这个方法的缺点是用户名和密码的数据传输采用的是Base64编码(可读文本),是非常不安全的。
DIGEST-摘要验证:数据采用MD5对用户名和密码进行加密,然后再传输,显然这种方法很安全。
FORM-表单验证:可以使用自定义的登陆页面,但用户名对应的文本框名称必须是j_username,密码为j_password,且表单action值为j_security_check。
在web.xml中加入<security-role>元素-指明这个Web应用应用的所有角色的名字
< description > The role that is required to lon in to the Administration Application. </ description >


</ security-role >

你可以调用HttpRequeset接口的getRemoteUser()方法返回当前用户的名字:<%=request.getRemoteUser()%>
内存域-由org.apache.catalina.realm.MemoryRelam类实现
小猫启动时,自动读取<%CATALINA_HOME%>/conf/tomcat-users.xml文件,要在Web应用中使用,可以在对应的<Context>元素内加入如下内容:<Realm className="org.apache.catalina.realm.MemoryRelam"/>
JDBC域-通过JDBC驱动从数据库中直接读取验证信息,通过验证后,信息会存储在session中。
在mysql中新建两张表:
create table usr_roles{usr_name varchar ( 15 ) not null ,role_name varchar ( 15 ) not null ,
primary key ( user_name ,role_name)};

然后在server.xml中加入:



