1.准备TLD文件
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library from ams</description>
<tlib-version>1.0</tlib-version>
<short-name>ams</short-name>
<uri>http://www.ams.com/tags</uri>
<tag>
<description>权限校验执行标签</description>
<name>demoTag</name>
<tag-class>com.sly.accountmanager.tag.DemoTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>accessPage</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2. 创建标签类
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import com.sly.accountmanager.common.constant.CommonConstant;
import com.sly.accountmanager.system.model.User;
/**
*
* @author sly
* @time 2019年1月28日
*/
public class DemoTag extends TagSupport {
private static final long serialVersionUID = -4710136810091643261L;
/**
* _权限访问页面
*/
private String accessPage;
@Override
public int doStartTag() throws JspException {
//获取session
HttpSession session = this.pageContext.getSession();
User user = (User) session.getAttribute(CommonConstant.SESSION_USER);
System.out.println(user.getUsername());
if(accessPage.equals("/haha")){
//有权限执行标签体
return EVAL_BODY_INCLUDE;
}else{
//无权限跳过标签体
return SKIP_BODY;
}
}
public String getAccessPage() {
return accessPage;
}
public void setAccessPage(String accessPage) {
this.accessPage = accessPage;
}
}
这里例子里写的是如果accessPage属性是"/哈哈"就保留标签里的内容
3.jsp页面引入标签库
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="ams" uri="http://www.ams.com/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ams:demoTag accessPage="/haha"><h3>haha</h3></ams:demoTag>
<ams:demoTag accessPage="/lala"><h3>lala</h3></ams:demoTag>
</body>
</html>
这里需要引入标签库,标签库的url来自tld文件中的uri
4.测试
结果只显示了一个.
特此记录以备不时之需!