JSTL 自定义

自定义标签

package taglibs;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class DateTag implements Tag{
 private PageContext pageContext;
 private Tag tag;
 
 public int doEndTag() throws JspException {
  try{
   Date date=new Date();//定义日期
   SimpleDateFormat dateFormater=new SimpleDateFormat("yyyy年MM月dd日");//日期格式
   pageContext.getOut().print(dateFormater.format(date));
  }catch(IOException e){
   e.printStackTrace();
  }
  return Tag.EVAL_PAGE;
 }

 public int doStartTag() throws JspException {//开始标签
  return Tag.SKIP_BODY;
 }

 public Tag getParent() {
  return null;
 }

 public void release() {}

 public void setPageContext(PageContext pageContext) {
  this.pageContext=pageContext;
 }

 public void setParent(Tag parent) {
  this.tag=parent;
 }
}

 

标签库配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
                        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
 <tlib-version>1.0</tlib-version>
 <jsp-version>1.2</jsp-version>
 <short-name>dateTagExample</short-name>
 <uri>/mytags</uri>
 <tag>
  <name>date</name>
  <tag-class>taglibs.DateTag</tag-class>
  <body-content>empty</body-content>
 </tag>
</taglib>

 


调用自定义标签

<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312" pageEncoding="gb2312"%>
<%@ taglib uri="/WEB-INF/datetag.tld"  prefix="mytags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>自定义标签示例</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    <font size="2">
    下面是使用自定义标签输出的内容:<br>
    <mytags:date/>
    </font>
  </body>
</html>

 

posted @ 2011-10-21 17:07  残星  阅读(423)  评论(0编辑  收藏  举报