jstl

    xiaoxiao2026-03-06  5

    前言

    在我们的日常开发中,虽然标准jstl库能满足我们的大部分需求,但是在没办法满足的时候就需要我们 使用自定的标签,

    说明

    这里只演示最简单的标签开发流程,便于熟悉开发流程

    开发流程

    结构图

    编写标签类

    需要继承TagSupport类或者其他实现了jsptag接口的类或者接口.

    /** * 自定义标签类 * @author EumJi * */ public class ExampleTag extends TagSupport{ //复写dostarttag @Override public int doStartTag() throws JspException { try { //向浏览器写内容 pageContext.getOut().print("这是我的第一个标签!"); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } }

    编写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 exercising SimpleTag handlers.</description> <!-- 标签版本 --> <tlib-version>1.0</tlib-version> <!--简称 --> <short-name>SimpleTagLibrary</short-name> <!-- 路径 --> <uri>/example</uri> <tag> <!-- 标签描述 --> <description>Outputs 第一个标签</description> <!-- 标签名 --> <name>first</name> <!-- 标签对应的实体类 --> <tag-class>com.jsu.tag.ExampleTag</tag-class> <!-- 标签里的内容 tagdependent:标签体内容直接被写入BodyContent,由自定义标签类来进行处理,而不被JSP容器解释. empty:空标记,即起始标记和结束标记之间没有内容. scriptless:接受文本、EL和JSP动作. JSP:接受所有JSP语法,如定制的或内部的tag、scripts、静态HTML、脚本元素、JSP指令和动作。 --> <body-content>empty</body-content> </tag> </taglib>

    在jsp页面中引入标签并使用

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="/example" prefix="ex" %>> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>测试案例</h1> <ex:first/> </body> </html>

    实验结果

    更多代码

    请移步:源代码

    最新回复(0)