自定义一个简单的标签
程序员文章站
2022-06-08 15:41:52
...
创建工程
Dynamic Web Project
MyTag.java ##
package com.foot.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public final class MyTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().println("hello Tag!");
//getJspContext() 返回使用自己定义的标签的那张jsp
}
}
mytag.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>My tag library exercising SimpleTag handlers.</description>
<!-- 标签的版本 -->
<tlib-version>1.0</tlib-version>
<!-- 标签的名字 -->
<short-name>MyTag</short-name>
<!-- 标签的唯一id值 -->
<uri>http://MyTag.com/core</uri>
<tag>
<description>Outputs Hello, World</description>
<!-- 以下3个重要 -->
<name>helloWorld</name>
<tag-class>com.foot.tag.MyTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://MyTag.com/core" prefix="mytag"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<mytag:helloWorld/>
</body>
</html>