控制客戶端訪問是開發一個基於B/S的架構的系統的開發者必須考慮的問題
我采用定制標簽庫和和配置文件來解決這個問題
例如
<%@ taglib uri="http://mytag" PRefix="custTag" %>
<html>
<head>
<title>test</title>
</head>
<body >
<form name="form
<table width="
<tr>
<td>
<custTag:JspSecurity elementName="employeedetail" >
<input type="button" name="detail" value="詳細" >
</custTag:JspSecurity>
<custTag:JspSecurity elementName="employeemodify" >
<input type="button" name="modify" value="修改" >
</custTag:JspSecurity>
</td>
</tr>
</table>
<br>
</form>
</body>
下面XML配置文件內容表示對角色為common的用戶
<?xml version="
<security>
<htmlElement name="employeedetail" >
<roleName name="common" />
<roleName name="admin" />
</htmlElement>
<htmlElement name="employeemodify" >
<roleName name="admin" />
</htmlElement>
</security>
定制標簽類JspSecurityTag繼承了BodyTagSupport類
Pagekage com
import javax
import javax
import java
import org
import org
import org
import java
import javax
public class JspSecurityTag extends BodyTagSupport {
//保存從XML文件中取到角色和頁面元素的對應集合
private static ArrayList roleList;
//頁面元素的名稱
private String elementName;
public void setElementName(String str)
{
this
}
public int doAfterBody() throws JspException{
if(roleList==null)
{
roleList=getList();
}
try{
//如果認證通過就顯示標簽正文
if(isAuthentificated(elementName))
{
if(bodyContent != null){
JspWriter out=bodyContent
bodyContent
}else
{
}
}
}catch(Exception e){
throw new JspException();
}
return SKip_BODY;
}
//從XML配置文件中取到角色和頁面元素的對應
private ArrayList getList()
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory
DocumentBuilder db = null;
Document doc=null;
NodeList childlist = null;
String elementName;
String roleName;
int index;
ArrayList theList = new ArrayList();
try{
db = dbf
}catch(Exception e)
{
e
}
try{
doc = db
}catch(Exception e)
{
e
}
//讀取頁面元素列表
NodeList elementList = doc
for(int i=
{
Element name = ((Element)elementList
//頁面元素的名稱
elementName = name
//該頁面元素對應的有權限的角色的列表
NodeList rolNodeList = ((NodeList)name
for(int j=
{
//有權限的角色的名稱
//roleName = ((Element)rolNodeList
roleName = ((Element)rolNodeList
theList
}
}
return theList;
}
//檢查該角色是否有該頁面元素的權限
private boolean isAuthentificated(String elementName)
{
String roleName = "";
//在用戶登陸時把該用戶的角色保存到session中
roleName=this
// roleList包含elementName屬性為elementName
if(roleList
{
return true;
}
}
return false;
}
//表示角色和頁面元素的對應的關系的內部類
class ElementAndRole{
String elementName;
String roleName;
public ElementAndRole(String elementName
{
this
this
}
public boolean equals(Object obj)
{
return(((ElementAndRole)obj)
}
}
}
在標簽庫能被JSP頁面使用前
<taglib>
<taglib
<taglib
/WEB
</taglib
</taglib>
下面是使用這個標簽庫對應的TLD文件
<?xml version="
<!DOCTYPE taglib
PUBLIC "
"
<taglib>
<tlibversion>
<jspversion>
<shortname>myTag</shortname>
<uri/>
<tag>
<name>JspSecurity</name>
<tagclass>com
<info>
JspSecurityTag
</info>
<attribute>
<name>elementName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20602.html