自定义JSTl标签-----满足自身需求(JSTL标签库无法满足需求时)
一.JSTL是:
apache开发的一套jsp标签,后来捐献给了sun,sun将其命名为jstl
二.JSTL的使用(ideal中)
1.导入jar包到pom文件中:
<!--jstl的jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
2.jsp页面中使用taglib指令来导入jstl标签库中的标签
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
3.常见标签:
if标签: <c:if test=""></c:if>
forEach标签:<c:forEach var="" items=""></c:forEach>
choose标签:<c:choose></c:choose>
三:自定义jstl标签
步骤:
1,准备好Java方法,继承BodyTagSupport类
package cn.com.util; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.tagext.BodyTagSupport; import cn.com.dao.IPrivilegeDAO; import cn.com.entity.Privilege; import cn.com.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.findPrivilegeIdByUsername(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"); } }
2,创建一个tld文件,将准备的方法添加到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.com.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,然后就可以在jsp中调用了
然后你就能用了:
<Authorize:authorize URL="/role/addRole">
<a href="/role/addRole">添加角色</a>
</Authorize:authorize>
菜鸟一只,请多多关照,谢谢各路大神。。。!!!