web自定义标签

   1:为什么需求自定义标签?

   当jsp的内置标签和jstl标签库内的标签都满足不了需求,这时候就需要开发者自定义标签。

 2:首先引入我们的web小配置

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">
<description>
    <![CDATA[security Tags]]>
</description>
<tlib-version>1.0</tlib-version>
<short-name>security</short-name>
<uri>http://www.springsecurity.org/jsp</uri>
<tag>
    <description>
        <![CDATA[authorize Tag]]>
    </description>
    <name>authorize</name>
    <tag-class>
        cn.struts.util.AuthorizeTag
    </tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>URL</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
        <type>java.lang.String</type>
    </attribute>
</tag>
</taglib>  

3:工具类

public class AuthorizeTag  extends BodyTagSupport {
	//你提供一个用户名字,我给一个用户拥有的权限集合,并且操作是在权限的DAO中
	private IPrivilegeDao privilegeDao;
	    private String URL;
	    public String getURL() {  
	        return URL;  
	    }
	    public void setURL(String uRL) {  
	        URL = uRL;  
	    }  
	    @Override  
	    public int doStartTag() {
	        // 如果URL不空就显示URL,否则就不显  
	        if (null != URL) {
	        	getUserDao();
	        	HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
				UserInfo info=(UserInfo)request.getSession().getAttribute("userinfo");
	        	List<Privilege> list = privilegeDao.fimdAllPrivilegeByUserId(info.getUserid());
	        	for (Privilege item : list) {
					if(item.getUrl().equals(URL)){
						  //正确渲染该标签
						  return EVAL_BODY_INCLUDE;  
					}
				}
	        }  
	        return this.SKIP_BODY;  
	    }
		public void getUserDao() {
			  WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
			   privilegeDao=(IPrivilegeDao)applicationContext.getBean("IPrivilegeDao");
		}

  4:jsp

//引入我们web中自定义的链接
<%@taglib prefix="custom" uri="http://www.springsecurity.org/jsp" %>

//根据点击来获取我们这一列中带有URL属性的表如果他的URL不为空就显示咱们的 " 添加角色 "
<custom:authorize URL="/role/addRole">
	<a href="#">添加角色</a>
</custom:authorize>

  

  

原文地址:https://www.cnblogs.com/1612ss/p/7898391.html