一、使用TagSupport类案例解析
1.自定义Tag使用jdbc连接mysql数据库
1.1定义标签处理器类
package com.able.tag; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class DBconnectionTag extends TagSupport { private String driver;// 连接驱动 private String url;// 连接db地址 private String password;// 连接db密码 private String sql;// 查询sql private String username;// 连接db用户名 Connection conn = null; Statement stmt = null; ResultSet rs = null; @Override public int doEndTag() throws JspException { try { Class.forName(this.driver); conn = DriverManager.getConnection(this.url,this.username,this.password); stmt = conn.createStatement(); rs = stmt.executeQuery(this.sql); if (rs != null) { while (rs.next()) { pageContext.getOut().print(rs.getString("cname")+"<br/>"); } } return EVAL_PAGE; } catch (Exception e) { e.printStackTrace(); return SKIP_PAGE; } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
1.2 在tag.tld文件中添加tag标签
<tag> <name>DBconnectionTag</name><!-- 定义标签名 --> <tag-class>com.able.tag.DBconnectionTag</tag-class> <body-content>empty</body-content> <!-- 定义标签体为空 --> <attribute> <name>driver</name> <required>true</required> <rtexprvalue>true</rtexprvalue><!-- 可以使用el表达式接收参数 --> </attribute> <attribute> <name>url</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>username</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>password</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>sql</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
1.3 定义jsp,页面引入标签库,并定义标签
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <tm:DBconnectionTag url="jdbc:mysql://192.168.9.223:3306/test_2016" driver="com.mysql.jdbc.Driver" username="root" password="ablejava" sql="select * from course"/> <br/> <br> </body> </html>
2.forEach循环遍历输出集合
2.1 定义自定义标签处理器类
package com.able.tag; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class ForEachTag extends TagSupport { private String var; private Iterator<?> iterator; public void setItem(Object item) { if (item instanceof Map) { Map items = (Map) item; this.iterator = items.entrySet().iterator(); } else { Collection<?> c = (Collection) item; this.iterator = c.iterator(); } } @Override public int doStartTag() throws JspException { if (this.process()) return EVAL_BODY_INCLUDE; else return EVAL_PAGE; } @Override public int doAfterBody() throws JspException { if (this.process()) { return EVAL_BODY_AGAIN; } else { return EVAL_PAGE; } } private boolean process() { if (null != iterator && iterator.hasNext()) { Object item = iterator.next(); pageContext.setAttribute(var, item); return true; } else { return false; } } public String getVar() { return var; } public void setVar(String var) { this.var = var; } }
2.3 在tld文件中定义标签
<tag> <name>foreach</name> <tag-class>com.able.tag.ForEachTag</tag-class> <body-content>JSP</body-content> <attribute> <name>var</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>item</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <!-- <type>java.lang.Object</type> --> <type>java.util.Collection</type> </attribute> </tag>
2.4 在jsp页面定义循环标签
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <% List<String> list = new ArrayList<String>(); list.add("aa"); list.add("bb"); list.add("cc"); Map map = new HashMap(); map.put("1","a"); map.put("2","b"); map.put("3","c"); map.put("4","b"); %> <tm:foreach var="hi" item="<%=map %>"> <h1>${hi }</h1> </tm:foreach> <br/> <br> </body> </html>
3.定义Iterator循环输出数组
3.1定义标签处理器类
package com.able.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class IteratorTagDemo extends TagSupport { private String var; private String[] items; private int i =1; @Override public int doStartTag() throws JspException { if (items != null && items.length>0) { pageContext.setAttribute("name", items[0]); return EVAL_BODY_INCLUDE; } else { return SKIP_BODY; } } @Override public int doAfterBody() throws JspException { if (i<items.length) { pageContext.setAttribute("name", items[i]); i++; return EVAL_BODY_AGAIN; } else { return SKIP_BODY; } } @Override public int doEndTag() throws JspException { // TODO Auto-generated method stub return super.doEndTag(); } public String getVar() { return var; } public void setVar(String var) { this.var = var; } public String[] getItems() { return items; } public void setItems(String[] items) { this.items = items; } }
3.2 在.tld文件中定义标签
<tag> <name>IteratorTagDemo</name><!-- 定义标签名 --> <tag-class>com.able.tag.IteratorTagDemo</tag-class> <body-content>scriptless</body-content> <!-- 定义标签体为空 --> <attribute> <name>var</name> <required>true</required> </attribute> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
3.3在jsp页面定义Tag
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <% String[] nbastar = {"jordan","kobar"}; pageContext.setAttribute("nbastar", nbastar); %> <tm:IteratorTagDemo items="${nbastar }" var="name"> ${name } </tm:IteratorTagDemo> <br/> <br> </body> </html>
4.自定义Tag实现防盗链
4.1自定义标签处理器类
package com.able.tag; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class SkipPageOrEvalPageTag extends TagSupport { @Override public int doEndTag() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); String referer = request.getHeader("referer"); String url = "http://"+request.getServerName(); if (referer != null && referer.startsWith(url)) { return EVAL_PAGE; } else { try { pageContext.getOut().print("盗链"); } catch (IOException e) { e.printStackTrace(); } } return SKIP_PAGE; } }
4.2在.tld文件中定义tag标记
<tag> <name>SkipPageOrEvalPageTag</name><!-- 定义标签名 --> <tag-class>com.able.tag.SkipPageOrEvalPageTag</tag-class> <body-content>empty</body-content> <!-- 定义标签体为空 --> </tag>
4.3定义访问连接的SkipPageOrEvalPageAccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <!-- 防盗链 --> <a href="http://localhost/JSP_Tag_Demo/SkipPageOrEvalPage.jsp">防盗链</a> <br/> <br> </body> </html>
4.4定义访问成功后的SkipPageOrEvalPage.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <!-- 防盗链 --> <tm:SkipPageOrEvalPageTag/> <h1>SkipPageOrEvalPage标签处理学习</h1> <br/> <br> </body> </html>
二、使用SimpleTagSupport实现自定义Tag
1.继承SimpleTagSupport类实现循环输出集合或数组
1.1定义标签处理器类
package com.able.simpleTag; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class foreachAll extends SimpleTagSupport { private Object items; private String var; private Collection collection; public void setItems(Object items) { this.items = items; if (items instanceof Collection) {//list set collection=(Collection) items; } if (items instanceof Map) { Map map=(Map) items; collection =map.entrySet();//set } if (items instanceof Object[]) { Object obj[]=(Object[]) items; collection=Arrays.asList(obj); } if (items.getClass().isArray()) { this.collection=new ArrayList(); int length=Array.getLength(items); for (int i=0; i<length ; i++) { Object value=Array.get(items, i); this.collection.add(value); } } } public void setVar(String var) { this.var = var; } @Override public void doTag() throws JspException, IOException { Iterator it=this.collection.iterator(); while (it.hasNext()) { Object value=it.next(); this.getJspContext().setAttribute(var, value); this.getJspBody().invoke(null); } } }
1.2定义.tld文件中添加标签
<tag> <name>simpleforeachAll</name> <tag-class>com.able.simpleTag.foreachAll</tag-class> <body-content>scriptless</body-content> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>var</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
1.3定义jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <% List<String> list = new ArrayList<String>(); list.add("aa"); list.add("bb"); list.add("cc"); Map map = new HashMap(); map.put("1","a"); map.put("2","b"); map.put("3","c"); map.put("4","b"); int arr[]={1,2,3,4,5}; request.setAttribute("arr", arr); %> <br/> <br> <tm:simpleforeachAll var="i" items="${arr }">${i }</tm:simpleforeachAll> </body> </html>
2.使用SimpleTagSupport实现防盗链
2.1定义标签处理器类
package com.able.simpleTag; import java.io.IOException; import java.sql.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.SkipPageException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class RefererTag extends SimpleTagSupport { private String site; private String page; public void setSite(String site) { this.site = site; } public void setPage(String page) { this.page = page; } @Override public void doTag() throws JspException, IOException { PageContext pageContext =(PageContext) this.getJspContext(); HttpServletRequest httpServletRequest=(HttpServletRequest) pageContext.getRequest(); HttpServletResponse httpServletResponse=(HttpServletResponse) pageContext.getResponse(); //1.referer String referer=httpServletRequest.getHeader("referer"); if (referer==null || !referer.startsWith(site)) { if (page.startsWith(httpServletRequest.getContextPath())) { httpServletResponse.sendRedirect(page); return; }else if (page.startsWith("/")) { httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+page); }else{ httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/"+page); } throw new SkipPageException(); } } }
2.2 定义.tld文件
<tag> <name>referer</name> <tag-class>com.able.simpleTag.RefererTag</tag-class> <body-content>empty</body-content> <attribute> <name>site</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>page</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
2.3定义refererAccess.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <!-- 防盗链 --> <a href="http://localhost/JSP_Tag_Demo/Referer.jsp">防盗链</a> <br/> <br> </body> </html>
2.4定义访问页面referer.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <!-- 防盗链 --> <tm:referer site="" page=""/> <br/> <br> </body> </html>
三、使用BodyTagSupport实现自定义Tag
1.继承BodyTagSupport实现简单数据输出
1.1定义标签处理器类
package com.able.bodyTag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; public class BodyTagSupportTag extends BodyTagSupport { private BodyContent bodyContent; @Override public int doEndTag() throws JspException { String content = bodyContent.getString(); System.out.println(content); String newStr = "www.cnblogs.com/izhongwei"; JspWriter jspWriter= bodyContent.getEnclosingWriter(); try { jspWriter.write(newStr); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return EVAL_PAGE; } public BodyContent getBodyContent() { return bodyContent; } public void setBodyContent(BodyContent bodyContent) { this.bodyContent = bodyContent; } }
1.2在.tld文件中定义标签
<tag> <name>bodyTag</name><!-- 定义标签名 --> <tag-class>com.able.bodyTag.BodyTagSupportTag</tag-class> <body-content>scriptless</body-content> <!-- 定义标签体为空 --> </tag>
1.3定义jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%-- <%@taglib uri="http://www.able.com" prefix="tm" %> --%> <%-- <%@ taglib prefix="tm" uri="/WEB-INF/tlds/online.tld" %> --%> <%@taglib prefix="tm" uri="/WEB-INF/tag.tld" %> <!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> <tm:bodyTag> hello </tm:bodyTag> <br/> <br> </body> </html>
源码下载地址:https://github.com/ablejava/jsp-Tag
git克隆地址:https://github.com/ablejava/jsp-Tag.git