JSP自己定義標簽入門實例具體解釋
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="[email protected]
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();
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>" + 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
JSP自己定義標簽入門實例具體解釋