java:tag 自定義標籤應用

一,tag類css

1.1 TagMy標籤類,格式化當前日期並輸出  
package com.dkt.tag;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;


/*
 * doStartTag()               SKIP_BODY執行doEndTag()跳過標籤體
 *                                        EVAL_BODY_INCLUDE 執行標籤體
 * doAfterBody()            EVAL_BODY_AGAIN 循環執行標籤體
 * 								      SKIP_BODY  不執行標籤體,執行doEndTag()
 * doEndTag()                SKIP_PAGE   不執行jsp剩餘的頁面
 * 							          EVAL_PAGE   執行剩餘的頁面
 * 
 */
public class TagMy  extends TagSupport{
	private String format;
	public int doStartTag() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		String nowdate =  simpleDateFormat.format(new Date());
		JspWriter out = pageContext.getOut();
		try {
			out.print("Hello 世界!!");
			out.print(nowdate);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.SKIP_BODY;
	}
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}
	public int doEndTag() throws JspException {
		return super.doEndTag();
	}
	public String getFormat() {
		return format;
	}
	public void setFormat(String format) {
		this.format = format;
	}
	
} 
1.2 ForTag 標籤類,自定義<c:foreach>標籤,循環輸出 
package com.dkt.tag;

import javax.servlet.jsp.tagext.TagSupport;


public class FroTag  extends TagSupport{
	private int start;
	private int end;
	private String var;
	
	public int doStartTag(){
		System.out.println("doStartTag()"+start);
		if(start<=end){
			pageContext.setAttribute(var, start);
			start++;
			return super.EVAL_BODY_INCLUDE;
		}else {
			return super.SKIP_BODY;
		}
		//執行doAfterBody()
	}
	public int doAfterBody() {
		if(start<=end){
			pageContext.setAttribute(var, start);
			start++;
			System.out.println("doAfterBody()"+start);
			return super.EVAL_BODY_AGAIN;
		}else {
			return super.SKIP_BODY;
		}
	}
	public int doEndTag(){
		System.out.println("doEndTag()"+start);
		return super.EVAL_PAGE;	
	}
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getEnd() {
		return end;
	}
	public void setEnd(int end) {
		this.end = end;
	}
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
}
1.3 IteratorTag標籤類,迭代集合,所有循環輸出顯示在頁面  
package com.dkt.tag;

import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class IteratorTag  extends TagSupport{
	private String scope;
	private String var;
	private ArrayList  list = null;
	
	Iterator it = null;
	public int doStartTag()  {
		/*if (("page").equals(scope)) {
			list = (ArrayList)pageContext.getAttribute(list,pageContext.PAGE_SCOPE);
		}else if(("request").equals(scope)){
			list = (ArrayList)pageContext.getAttribute(list,pageContext.REQUEST_SCOPE);
		}else if(("session").equals(scope)){
			list = (ArrayList)pageContext.getAttribute(list,pageContext.SESSION_SCOPE);
		}else if(("application").equals(scope)){
			list = (ArrayList)pageContext.getAttribute(list,pageContext.APPLICATION_SCOPE);
		}*/
	    it = list.iterator();
		return super.EVAL_BODY_INCLUDE;
	}
	
	public int doAfterBody()  {
		if (it.hasNext()) {
			Object next = it.next();
			pageContext.setAttribute(var, next);
			return super.EVAL_BODY_AGAIN;
		}else {
			return super.SKIP_BODY;
		}
	}
	public int doEndTag() throws JspException {
		return super.doEndTag();
	}

	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public ArrayList getList() {
		return list;
	}
	public void setList(ArrayList list) {
		this.list = list;
	}
}
1.4 QueryTag 標籤類,根據表名,查詢數據庫,並由表格輸出到頁面  
package com.dkt.tag;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.dkt.util.DButil;

public class QueryTag  extends TagSupport{

	private String tableName;
	public int doStartTag() {
		DButil dButil = new DButil();
		Connection conn  = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		conn = dButil.createConn();
		String sql = "select  *  from  "+tableName;
		try {
			ps = conn.prepareStatement(sql);
			ResultSetMetaData rsmd = ps.getMetaData();//獲得表結構
			rs = ps.executeQuery();
			JspWriter out = pageContext.getOut();
			out.print("<table border='1px' width='60%'  align='center'><tr>");
			for (int i = 0; i < rsmd.getColumnCount(); i++) {//字段數量
				out.print("<th>"+rsmd.getColumnName(i+1)+"</th>");//字段名字
			}
			out.print("</tr>");
			while(rs.next()){
				out.print("<tr>");
				for (int i = 0; i < rsmd.getColumnCount(); i++) {
					out.print("<td>"+rs.getObject(i+1)+"</td>");
				}
				out.print("</tr>");
			}
			
			out.print("</table>");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.SKIP_BODY;
	}
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}
	public int doEndTag() throws JspException {
		return super.doEndTag();
	}
	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	
}

二,hellotag.tldhtml

文件 hellotag.tld 放在WEB-INF目錄下,與web.xml同級java

<?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>1.2</jsp-version>
	 <short-name>hello</short-name>
	 <uri>hello</uri>
	 <!-- TagMy自定義標籤類 -->
	 <tag>
	 	<name>hello</name>    <!-- 標籤名 -->
	 	<tag-class>com.dkt.tag.TagMy</tag-class>
	 	<body-content>empty</body-content> <!-- 是否有標籤體 jsp/empty -->
	 	<!-- 有屬性的標籤訂義 -->
	 	<attribute>
	 		<name>format</name>
	 		<required>true</required><!-- 表示標籤是否必須 -->
	 		<rtexprvalue>true</rtexprvalue><!-- 表示是否能夠使用表達式  el/jsp -->
	 	</attribute>
	 </tag>
	 <!-- FroTag -->
	 <tag>
	 		<name>formy</name>
	 		<tag-class>com.dkt.tag.FroTag</tag-class>
	 		<body-content>jsp</body-content>
	 		<attribute>
	 			<name>start</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 		<attribute>
	 		    <name>end</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 		<attribute>
	 			<name>var</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 </tag>
	 <!-- IteraterTag -->
	 	 <tag>
	 		<name>iteratormy</name>
	 		<tag-class>com.dkt.tag.IteratorTag</tag-class>
	 		<body-content>jsp</body-content>
	 		<attribute>
	 			<name>list</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 		<attribute>
	 		    <name>scope</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 		<attribute>
	 			<name>var</name>
	 			<required>true</required>
	 			<rtexprvalue>true</rtexprvalue>
	 		</attribute>
	 </tag>
	 <!-- 查詢數據庫的表並輸出 -->
	 <tag>
	 	<name>query</name>
	 	<tag-class>com.dkt.tag.QueryTag</tag-class>
	    <body-content>empty</body-content>
	 	<attribute>
	 		<name>tableName</name>
	 		<required>true</required>
	 		<rtexprvalue>true</rtexprvalue>
	 	</attribute>
	 </tag>
</taglib>

 三,jsp web

index.jsp  開啓服務器,直接訪問項目下的index.jsp頁面便可顯示自定義標籤sql

在jsp頁面導入自定義標籤數據庫

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.dkt.entity.UserInfo"%>
<%@ taglib uri="hello" prefix="hello" %>
<%
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 'index.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>
  
   <hello:hello format="yyyy-MM-dd HH:mm:ss a"/><br/>
   	<hr/>
	formy:<hello:formy end="10" var="item1" start="1">
				${item1 }----
	</hello:formy>   	
	<hr/>
		iterator:<%
			ArrayList list = new ArrayList();
			list.add(new UserInfo(0,"小白","123456","",""));
			list.add(new UserInfo(1,"小白111","353456","",""));
			list.add(new UserInfo(2,"小白222","532456","",""));
			list.add(new UserInfo(3,"小白333","532356","",""));
			list.add(new UserInfo(4,"小白444","123536","",""));

			request.setAttribute("list",list);
	 %>
	 <hello:iteratormy var="item2" scope="request" list="${list}">
				${item2.name}+++${item2.password }<br/>
	</hello:iteratormy>
	<hr/>
	
	<hello:query tableName="goods_table2"/>
	<hr>
	
  </body>
</html>

四,web.xml服務器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
  
  <welcome-file-list>
  	<welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
相關文章
相關標籤/搜索