jsp自定义标签

在web开发中难免会用到一系列的标签库,比如常用的jstl的标签库、struts提供的标签库。这些标签库都是厂商提供的,在开发中可以直接使用,然而在有些项目中需要开发者根据项目的需求来定制自己的标签。那么今天就来聊聊jsp中如何来自定义标签,以下以通过自定义标签来实现标签的过滤现实。

首先我们需要大致了解开发自定义标签所涉及到的接口与类的层次结构(其中SimpleTag接口与SimpleTagSupport类是JSP2.0中新引入的)。

一、创建web项目并引入jsp-api的jar包(可在tomcat的lib目录中获得)

二、创建RightFilter类实现Tag接口

方法说明:

  • doStartTag:表示标签的开始

  • doEndTag:表示标签的结束

  • setPageContext:用于注入PageContext对象

  • setParent:用于注入父标签

三、声明标签属性,这里我们只定义一个url属性

private String url;//添加get、set方法

private PageContext pageContext;//在set方法中对该属性进行赋值

四、实现doStartTag方法的逻辑

该方法是带int返回值的方法,其返回值在Tag接口中定义为如下:

public final static int SKIP_BODY = 0;//跳过该标签,及不显示标签的内容

public final static int EVAL_BODY_INCLUDE = 1;//正常解析标签的内容

@Override
public int doStartTag() throws JspException {
HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();
//获取登录的用户
User user=(User) request.getSession().getAttribute("user");
//判断该用户是否具有该权限
return user.hasRight(url)?EVAL_BODY_INCLUDE:SKIP_BODY;
}

五、编写tld文件

在web-info路径下的新建文件夹tld,在新建custom.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>自定义标签</description>
<display-name>自定义标签</display-name>
<!-- 版本 -->
<tlib-version>1.0</tlib-version>
<!-- 简单名称 -->
<short-name>custom</short-name>
<!-- 配置标签引入的地址:唯一 -->
<uri>http://www.woniuxy.com/jsp/tags</uri>

<tag>
<description>权限过滤</description>
<!-- 标签名称 -->
<name>rightFilter</name>
<!-- 标签的实现类 -->
<tag-class>com.customtag.view.RightFilter</tag-class>
<!--
1、tagdependent:标记体要看做是纯文本,所以不会计算EL,也不会出发标记/动作
2、JSP:能放在JSP中的东西都能放在这个标记体中
3、empty:即标记体为空
4、scriptless:这个标记不能有脚本元素,但可以有模板文本和EL,还可以是定制和标准动作
-->
<body-content>JSP</body-content>
<attribute>
<description>该标签对应的权限地址</description>
<!-- 自定义标签属性的名称 -->
<name>url</name>
<!-- 是否必须 -->
<required>true</required>
<!-- 是否支持表达式 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

</taglib>

六、使用(jsp)

  • 引入标签库:<%@ taglib uri="http://www.woniuxy.com/jsp/tags" prefix="custom" %>

  • 对需要用于权限过滤的标签进行包裹:

<custom:rightFilter url="userAction_delte.do">
<a href="userAction_delte.do">删除</a>
</custom:rightFilter>

  •     编写action

@WebServlet("/loginAction.do")
public class LoginAction extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user=new User();
//模拟设置权限
user.setRight("userAction_deltedd.do");
req.getSession().setAttribute("user", user);
resp.sendRedirect("test.jsp");
}

}

原文地址:https://www.cnblogs.com/woniuxy/p/8075091.html