java:tag 自定义标签应用

一,tag类

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.tld

文件 hellotag.tld 放在WEB-INF目录下,与web.xml同级

<?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 

index.jsp  开启服务器,直接访问项目下的index.jsp页面即可显示自定义标签

在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>
原文地址:https://www.cnblogs.com/nn369/p/8056858.html