JSP自定义标签的使用

JSP中引入自定义标签,主要是为了把JSP代码与HTML代码分离,两者混在一起,维护成本更高。
自定义标签有三步骤,1、写标签类 2、写定义标签的tld文件 3、JSP中使用
标签类Tablib.java:


package pocketdigi;

import java.io.IOException;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class Taglib extends SimpleTagSupport {
		private String name;
		private int age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		@Override
		public void doTag() throws JspException, IOException {
			// TODO Auto-generated method stub
			//自动调用doTag()方法
			JspContext context=getJspContext();
			JspWriter out=context.getOut();
			out.println("My Name is "+name+",I'm "+age+" years old");
			super.doTag();
		}
		
}

在WEB-INF目录下新建Taglib.tld文件,MyEclipse有模板,很方便:


<?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>2.0</jsp-version>
	<short-name>myTag</short-name>
	<!-- 短名好像没什么用 -->
	<uri>http://www.pocketdigi.com</uri>
	<!-- uri好像唯一就可以 -->
	<tag>
		<name>introduce</name>
		<!-- 标签名,jsp中引用时用 -->
		<tag-class>pocketdigi.Taglib</tag-class>
		<!-- 类名 -->
		<body-content>empty</body-content>
		<!-- 标签体内容,保持empty,暂时不了解其他值的用法 -->
		<attribute>
			<name>name</name>
			<required>true</required>
		</attribute>
		<attribute>
			<name>age</name>
			<required>true</required>
		</attribute>
		<!-- 两个属性,required是指是否必须设置 -->
	</tag>
</taglib>

在JSP中使用:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="myTagLib" prefix="myTag" %>
<html>
<head>
<title>My JSP '1.jsp' starting page</title>
</head>
	<body>
		<myTag:introduce age="15" name="Jim"/>
	</body>
</html>

执行结果:My Name is Jim,I’m 15 years old

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记