现在的位置: 首页 > 综合 > 正文

JSP自定义标签开发(二)—— HelloWorld 从TagSupport继承实现开发

2014年09月05日 ⁄ 综合 ⁄ 共 1707字 ⁄ 字号 评论关闭

按照下面的步骤进行:

 1)开发标签实现类

 2)编写标签描述文件,tld为扩展名。

 3)在Web.xml中映射标签库的使用。

 4)在JSP网页中调用标签。


1开发实现类(HelloTag.java

package com.wsy.tag;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
/**
 * 演示从TagSupport继承来开发标签
 */
public class HelloTag extends TagSupport {
/**
* 覆盖doStartTag方法
*/
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}

/**
* 覆盖doEndTag方法
*/
@Override
public int doEndTag() throws JspException {
String dateString = new Date().toLocaleString();
try {
pageContext.getOut().write(
"Hello World hellking.<br>现在的时间是:" + dateString);
} catch (IOException ex) {
throw new JspTagException(
"Fatal error:hello tag conld not write to JSP out");
}
return EVAL_PAGE;
}
}


2编写标签库描述(mytag.tld文件;路径:/WEB-INF/tlds/mytag.tld

<?xml version="1.0" encoding="gb2312"
?>
<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 web-jsptaglibrary_2_0.xsd" version="2.0">


<tlib-version>2.0</tlib-version>
<short-name>examples</short-name>
<uri>/demotag</uri>
<tag>
<name>hello</name>
<tag-class>com.wsy.tag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>


3
在Web.xml中映射标签库的使用。

<web-app>
...

<taglib>
<taglib-uri>/demotag</taglib-uri>
<taglib-location>/WEB-INF/tlds/mytag.tld</taglib-location>
</taglib>

...
</web-app>

4
在JSP网页中调用标签

<%@ taglib uri="/demotag" prefix="hello" %>
<%@ page contentType="text/html; charset=gb2312" language="java" %>
<html>
<head>

<title>first cumstomed tag</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<p>以下的内容从Taglib中显示:</p>
<p><i><hello:hello_int/></i></p>

此处是TagSupport标签的实现
<h1><hello:hello/></h1>
</body>
</html>

抱歉!评论已关闭.