自定義JSTl標簽-----滿足自身需求(JSTL標簽庫無法滿足需求時)
阿新 • • 發佈:2017-12-26
XML alt 圖片 val for taglib -c esc jar
一.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>
菜鳥一只,請多多關照,謝謝各路大神。。。!!!
自定義JSTl標簽-----滿足自身需求(JSTL標簽庫無法滿足需求時)