码迷,mamicode.com
首页 > Web开发 > 详细

JSP标签库

时间:2015-09-02 21:54:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

step1:

  定义一个标签处理类:改类必须实现SimpleTag接口,在实际中是拓展它的子类SimpleTagSupport。复写doTag方法

public class MyTag extends SimpleTagSupport {

@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.print("<b>hello</b>");
}

}

 

step2:

  一旦定义了标签处理类,下一个任务便是向服务器标识这个类,并将其与特定的XML标记名称相关联。这任务是通过一个XML格式的TLD文件来完成的。该文件包含固定的信息(如XML Schema实例声明)、一个任意短的库名称、一段简的描述及一系列标签描述,可以放在WEB-INF下面的目录里

  

<?xml version="1.0"?>
<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>
This exposes JSON util functions from the Struts JSON plugin
</description>

<tlib-version>1.0</tlib-version>

<short-name>mytld</short-name>
<tag>
<description>out put hello</description>
<name>test</name>
<tag-class>cn.donghua.jstl.MyTag</tag-class>
<body-content>empty</body-content>
</tag>

</taglib>

 

step3:

  jsp文件。引入标签<%@ taglib uri="..."  prefix="..."%>

  

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>My JSP ‘tldTest.jsp‘ starting page</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>
<%@ taglib uri="/WEB-INF/tlds/mytld.tld" prefix="mytest" %>
<mytest:test/>
</body>
</html>

访问输出:hello 

若要为标签库添加属性如<mytest:test attr="value"/>则需要在MyTag中增加属性set方法,如加了length属性则在Mytag有setLength()

 


private int length;

public void setLength(String length) throws IOException{
this.length = Integer.parseInt(length);
JspWriter out = getJspContext().getOut();
out.print(length);
}

 

tld文件也要添加相应的属性说明:

<tag>
<description>out put hello</description>
<name>test</name>
<tag-class>cn.donghua.jstl.MyTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>length</name>
<required>false</required>
</attribute>
</tag>

jsp文件


<body>
<%@ taglib uri="/WEB-INF/tlds/mytld.tld" prefix="mytest" %>
<mytest:test length="56"/>
</body>

输出:56

JSP标签库

标签:

原文地址:http://www.cnblogs.com/daxiong225/p/4779410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!