JSP自己定义标签主要能用到的两个包
javax.servlet.jsp.*;javax.servlet.jsp.tagext.*;
自己定义标签<userInfo:showUserInfo/>实现对用户的展现。
效果图例如以下
private String userName;
private Integer age;
private String email;
public User(){
this.userName="张三";
this.email="zhangsan@163.com";
this.age=28;
}
创建自己定义标签类UserInfoTag.java
package com.test.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import com.test.entity.User;
public class UserInfoTag extends TagSupport {
private User user=new User();
@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
JspWriter out = this.pageContext.getOut();
try {
if (user == null) {
out.print("UserInfo Is Not Found......");
return SKIP_BODY;
}
out.println("<table width='500px' border='1' align='center'>");
out.println("<tr>");
out.println("<td width='20%'>Username:</td>");
out.println("<td>" + user.getUserName() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Age:</td>");
out.println("<td>" + user.getAge() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Email:</td>");
out.println("<td>" + user.getEmail() + "</td>");
out.println("</tr>");
out.println("</table>");
} catch (Exception e) {
throw new JspException(e.getMessage());
}
return super.doStartTag();
}
@Override
public int doEndTag() throws JspException {
// TODO Auto-generated method stub
return EVAL_PAGE;
}
@Override
public void release() {
// TODO Auto-generated method stub
super.release();
this.user=null;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
2在Web-Inf创建标签库描写叙述文件.tdl(Tag Library Description)
<?
xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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">
<tlib-version>1.0</tlib-version>
<jsp-version>3.0</jsp-version>
<short-name>userInfo</short-name>
<uri>mytaglib</uri>
<tag>
<name>showUserInfo</name>
<tag-class>com.test.tag.UserInfoTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>user</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3 配置web.xml
<jsp-config>
<taglib>
<taglib-uri>mytaglib</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
</taglib>
</jsp-config>
4 须要使用该标签的页面头部引入
<%@ taglib uri="/mytaglib" prefix="cc"%>
<userInfo:showUserInfo/>
标签说明
我们创建的UserInfoTag类继承了TagSupport类,而它又实现了Tag接口,Tag接口的生命周期由其所在的容器控制,例如以下:
setPageContext() 将所在jsp页面的pageContext注入进来,目的是为了在后面的方法中能够訪问到jsp页面对象的pageContext属性
setParent() 设置此标签的父标签
setAttribute() 将标签中的属性注入到此class的属性,不须要自己实现但要提供属性的get与set方法
doStartTag() 在開始标签属性设置后调用,假设返回SKIP_BODY则忽略标签之中的内容,假设返回EVAL_BODY_INCLUDE则将标签体的内容进行输出
doEndTag() 在结束标签之前调用,返回SKIP_PAGE跳过整个jsp页面后面的输出,返回EVAL_PAGE运行页面余下部分
release() 生命周期结束时调用
至此,一个简单的自己定义标签就实现了。源代码下载地址 http://download.csdn.net/detail/qiyejunlintian/8037433