JSP自定义一个简单标签教程
程序员文章站
2022-07-14 23:30:51
...
用JSP自定义标签库,输出当前时间,流程如下:
1.开发自定义的标签库类,自定义标签库必须继承javax.servlet.jsp.tagext.SimpleTagSupport
如NowTime.java
- package mckee;
- import java.io.IOException;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- public class NowTime extends SimpleTagSupport
- {
- public void doTag() throws JspException,IOException
- {
- getJspContext().getOut().print(new java.util.Date());
- }
- }
2.建立TLD文件,将建立的自定义tld放在WEB-INF或其任意子路径下,该文件会被自动加载,
如:nowtime.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>mytag</short-name>
- <uri>/mytag</uri><!-- 这个很重要,jsp页面就是根据uri来定位标签库的 -->
- <tag>
- <name>nowtime</name><!-- 定义标签名 -->
- <tag-class>mckee.NowTime</tag-class><!-- 定义标签处理类 -->
- <body-content>empty</body-content><!-- 定义标签体为空 -->
- </tag>
- </taglib>
3.在jsp页面中使用自定义标签
如tag-test.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ taglib uri="/mytag" prefix="mytag" %>
- <!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=UTF-8">
- <title>http://www.heatpress123.com</title>
- </head>
- <body>
- <mytag:nowtime/>
- </body>
- </html>
运行结果如下:
上一篇: spring security 实现免登陆功能 Spring
下一篇: 病毒式传播的八种方式