JSP自定义一个简单标签教程

阅读更多

用JSP自定义标签库,输出当前时间,流程如下:

1.开发自定义的标签库类,自定义标签库必须继承javax.servlet.jsp.tagext.SimpleTagSupport

如NowTime.java

  1. package mckee;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.jsp.JspException;
  6. import javax.servlet.jsp.tagext.SimpleTagSupport;
  7.  
  8. public class NowTime extends SimpleTagSupport
  9. {
  10. public void doTag() throws JspException,IOException
  11. {
  12. getJspContext().getOut().print(new java.util.Date());
  13. }
  14. }

2.建立TLD文件,将建立的自定义tld放在WEB-INF或其任意子路径下,该文件会被自动加载,

如:nowtime.tld

  1. xml version="1.0" encoding="UTF-8" ?>
  2.  xmlns="http://java.sun.com/xml/ns/j2ee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  5. version="2.0">
  6. A tag library exercising SimpleTag handlers.
  7. 1.0
  8. mytag
  9. /mytag
  10. nowtime
  11. mckee.NowTime
  12. empty
  13.  

3.在jsp页面中使用自定义标签

如tag-test.jsp

 
  
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%@ taglib uri="/mytag" prefix="mytag" %>
  3.  http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. </span><span class="pln" style="padding: 0px; margin: 0px;">http://www.heatpress123.com</span><span class="tag" style="padding: 0px; margin: 0px; color: #000088;">

运行结果如下:

你可能感兴趣的:(互联网,sns)