jsp自定义标签案例分析
1、演示传统自定义标签(jsp2.0以前的)
使用自定义标签控制页面内容(标签体)是否输出,利用doStartTag()的返回值控制
return this.SKIP_BODY; //忽略标签体
return this.EVAL_BODY_INCLUDE; //执行标签体
控制整个jsp的输出利用doEndTag()的返回值控制
return this.SKIP_PAGE; //跳过页面标签后余下的jsp代码
return this.EVAL_PAGE; //继续执行余下jsp代码
自定义标签实现内容(标签体)循环输出利用Tag子接口Iteration中定义的doAfterBody()和返回值EVAL_BODY_AGAIN,SKIP_BODY实现
先覆盖doStartTag()方法,返回EVAL_BODY_INCLUDE
覆盖doAfterBody()
[html]
public int doAfterBody() throws JspException {
times++;
int result = this.EVAL_BODY_AGAIN;
if(times>4){
result = this.SKIP_BODY;
}
return result;
}
自定义标签修改内容(标签体)EVAL_BODY_BUFFERED;
标签处理类:
继承BodyTagSupport
覆盖doStartTag(),并返回EVAL_BODY_BUFFERED;
覆盖doEndTag()
public int doEndTag() throws JspException {
BodyContent bc = this.getBodyContent();
String c = bc.getString();
c = c.toUpperCase();
JspWriter out = this.pageContext.getOut();
try {
out.write(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
return this.EVAL_PAGE;
}
2、需求:实现一个自定义标签功能:判断一个YYYY-MM-DD格式的日期修改为下面格式输出
年:YYYY
月:MM
日:DD
分析:
自定义标签处理类(Demo5.java)
package com.csdn.web.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
public class Demo5 extends BodyTagSupport {
@Override
public int doEndTag() throws JspException {
BodyContent bc = this.getBodyContent();
String b = bc.getString();
String[] data = b.split("-");
JspWriter out = this.pageContext.getOut();
try {
out.println("年:"+data[0]+"<br>");
out.println("月:"+data[1]+"<br>");
out.println("日:"+data[2]+"<br>");
} catch (IOException e) {
e.printStackTrace();
}
return Tag.EVAL_PAGE;
}
}
要转换的显示时间6.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/csdn" prefix="csdn"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>转换日期格式并输出</title>
</head>
<body>
<csdn:demo5>2012-11-17</csdn:demo5>
</body>
</html>
对应的标签模版csdn.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">
<tlib-version>1.0</tlib-version>
<short-name>csdn</short-name>
<uri>/csdn</uri>
<tag>
<name>demo5</name>
<tag-class>com.csdn.web.tag.Demo5</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
补充:Web开发 , Jsp ,