第一步:在web-inf下创建一个tld文件
<?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.tms.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>
第二步:创建一个类继承BodyTagSupport
package cn.tms.util; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.tagext.BodyTagSupport; import cn.tms.dao.IPrivilegeDAO; import cn.tms.dao.IRoleDAO; import cn.tms.entity.Privilege; import cn.tms.entity.UserInfo; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; //标签 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.findAllPrivilegeByUserId(info.getUserid()); System.out.println(list.size()); for (Privilege item : list) { System.out.println(URL+"=========================="); 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"); } }
第三步: 在页面上使用之前在页面上添加
<%@taglib prefix="Authorize" uri="http://www.springsecurity.org/jsp" %>
*注意:这里的URi的地址和web-inf里面配的地址保持一致
最后使用:
这里Authorize是你自己定义的
URL是传入到Authorize里的,然后和后台取到的url进行对比,如果一致就在页面上渲染此标签,不一致就不渲染此标签