下面將以權限的控制為例自定義一個標簽:
一、標簽類型
代碼如下:
<wxt:per uri="${pageContext.request.contextPath }/privilege/list"></wxt:per>
步驟:
1.自定義一個類PerssionTag 繼承SimpleTagSupport(自定義標簽一般都會繼承這個類)
代碼如下:
package cn.com.liveuc.privilege.tag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import cn.com.liveuc.privilege.model.Privilege;
import cn.com.liveuc.privilege.model.Resource;
import cn.com.liveuc.privilege.model.Role;
import cn.com.liveuc.privilege.model.User;
/**
*
* @說明 自定義標簽
*/
public class PerssionTag extends SimpleTagSupport {
//自定義標簽屬性,用於標簽傳入參數
private String uri;
//接收標簽傳入的參數
public void setUri(String uri) {
this.uri = uri;
}
@Override
public void doTag() throws JspException, IOException {
//獲取用戶登陸後保存的Session
PageContext page = (PageContext) this.getJspContext();
User user = (User) page.getSession().getAttribute("login");
//如果用戶登陸
if(user != null) {
//用戶登陸判斷用戶權限
List<String> list = new ArrayList<String>();
//獲取用戶的角色
Set<Role> role = user.getRole();
for(Role r:role) {
//獲取角色對應的權限
Set<Privilege> privilege = r.getPrivilege();
for(Privilege p:privilege) {
//獲取權限對應的資源
Set<Resource> res = p.getResource();
for(Resource re:res) {
list.add(re.getUri());
}
}
}
for(String ur:list) {
//判斷用戶的權限
if(ur.equals(uri)) {
this.getJspBody().invoke(null); //有權限輸出標簽體內容
}
}
}
}
}
2.在WEB-INF下創建tld文件描述標簽。
代碼如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<description><![CDATA["To make it easier to access dynamic data;
the Apache Struts framework includes a library of custom tags.
The tags interact with the framework's validation and internationalization features;
to ensure that input is correct and output is localized.
The Struts Tags can be used with JSP FreeMarker or Velocity."]]></description>
<display-name>"Struts Tags"</display-name>
<tlib-version>2.2.3</tlib-version>
<short-name>s</short-name>
<uri>/wxt</uri>
<tag>
<name>per</name><!-- 標簽名 -->
<tag-class>cn.com.liveuc.privilege.tag.PerssionTag</tag-class>
<body-content>scriptless</body-content>
<!-- 標簽屬性 -->
<attribute>
<name>uri</name><!-- 屬性名稱 -->
<required>true</required><!-- 是否必須 -->
<rtexprvalue>true</rtexprvalue><!-- 是否為動態標簽 -->
</attribute>
</tag>
</taglib>
3.運用標簽
在Jsp頁面導入標簽:
<A href="mailto:%@taglib prefix='wxt' uri='/wxt' %">%@taglib prefix="wxt" uri="/wxt" %</A>
運用標簽:
<wxt:per uri="${pageContext.request.contextPath }/user/list">
<a href="${pageContext.request.contextPath }/user/list" target="reight">用戶管理</a>
</wxt:per>
用戶權限包含uri資源的將會輸出標簽內容。