java jsp自定义标签

1、web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 6     <display-name>test_Servlet</display-name>
 7      <jsp-config>
 8         <taglib>
 9             <taglib-uri>kongxh_tag</taglib-uri>
10             <taglib-location>/WEB-INF/mytag.tld</taglib-location>
11         </taglib>
12     </jsp-config>
13     <!-- 配置欢迎界面 -->
14     <welcome-file-list>
15         <welcome-file>index.jsp</welcome-file>
16     </welcome-file-list>
17 </web-app>

2、tld的编写

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
 4     version="2.0">
 5     <tlib-version>1.0</tlib-version>
 6     <jsp-version>2.0</jsp-version>
 7     <short-name>firsttags</short-name>
 8     <tag>
 9         <name>IterTag</name>
10         <tag-class>test_servlet_package.tag.IterTag</tag-class>
11         <body-content>jsp</body-content>
12         <attribute>
13             <name>scope</name>
14             <required>true</required>
15             <rtexprvalue>true</rtexprvalue>
16         </attribute>
17         <attribute>
18             <name>id</name>
19             <required>true</required>
20             <rtexprvalue>true</rtexprvalue>
21         </attribute>
22         <attribute>
23             <name>name</name>
24             <required>true</required>
25             <rtexprvalue>true</rtexprvalue>
26         </attribute>
27     </tag>
28     <tag>
29         <name>MyBodyTag</name>
30         <tag-class>test_servlet_package.tag.MyBodyTag</tag-class>
31         <tei-class>test_servlet_package.tag.MyTagExtraInfo</tei-class>
32         <body-content>jsp</body-content>
33         <attribute>
34             <name>scope</name>
35             <required>true</required>
36             <rtexprvalue>true</rtexprvalue>
37         </attribute>
38         <attribute>
39             <name>id</name>
40             <required>true</required>
41             <rtexprvalue>true</rtexprvalue>
42         </attribute>
43         <attribute>
44             <name>name</name>
45             <required>true</required>
46             <rtexprvalue>true</rtexprvalue>
47         </attribute>
48     </tag>
49     <tag>
50         <name>MySimpleTag</name>
51         <tag-class>test_servlet_package.tag.MySimpleTag</tag-class>
52         <body-content>empty</body-content>
53         <attribute>
54             <name>format</name>
55             <required>true</required>
56             <rtexprvalue>true</rtexprvalue>
57         </attribute>
58     </tag>
59     <tag>
60         <name>MySimpleTagForIter</name>
61         <tag-class>test_servlet_package.tag.MySimpleTagForIter</tag-class>
62         <body-content>scriptless</body-content>
63         <attribute>
64             <name>scope</name>
65             <required>true</required>
66             <rtexprvalue>true</rtexprvalue>
67         </attribute>
68         <attribute>
69             <name>id</name>
70             <required>true</required>
71             <rtexprvalue>true</rtexprvalue>
72         </attribute>
73         <attribute>
74             <name>name</name>
75             <required>true</required>
76             <rtexprvalue>true</rtexprvalue>
77         </attribute>
78     </tag>
79     <tag>
80         <name>DynamicAttributesTag</name>
81         <tag-class>test_servlet_package.tag.DynamicAttributesTag</tag-class>
82         <body-content>empty</body-content>
83         <dynamic-attributes>true</dynamic-attributes>
84     </tag>
85 </taglib>
View Code

3、Tag的编写

IterTag:循环标签

 1 package test_servlet_package.tag;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 import javax.servlet.jsp.JspException;
 5 import javax.servlet.jsp.PageContext;
 6 import javax.servlet.jsp.tagext.TagSupport;
 7 public class IterTag extends TagSupport {
 8     /**
 9      * jsp 1.2 之前 的 做法 
10      */
11     private static final long serialVersionUID = 1L;
12     //接受属性名称
13     private String name;
14     //接受查找范围
15     private String scope;
16     private String id;
17     private Iterator<?> iter = null;
18     @Override
19     public int doStartTag() throws JspException {
20         Object value = null;
21         //是否是page范围
22         if ("page".equals(this.scope)) {
23             value = super.pageContext
24                     .getAttribute(name, PageContext.PAGE_SCOPE);
25         } else if ("request".equals(this.scope)) {
26             //是否是request范围
27             value = super.pageContext.getAttribute(name,
28                     PageContext.REQUEST_SCOPE);
29         } else if ("session".equals(this.scope)) {
30             //是否是session范围
31             value = super.pageContext.getAttribute(name,
32                     PageContext.SESSION_SCOPE);
33         } else {
34             //是否是application范围
35             value = super.pageContext.getAttribute(name,
36                     PageContext.APPLICATION_SCOPE);
37         }
38         //如果没有查到属性
39         if (value !=null && value instanceof List<?>) {
40             this.iter = ((List<?>)value).iterator();
41             if(iter.hasNext()){
42                 super.pageContext.setAttribute(this.id,iter.next());
43                 //找到属性,执行标签题内容
44                 return TagSupport.EVAL_BODY_INCLUDE;
45             }else{
46                 //找到属性,执行标签题内容
47                 return TagSupport.SKIP_BODY;
48             }
49         }else{
50             //不执行标签体内容
51             return TagSupport.SKIP_BODY;
52         }
53     }
54     public String getName() {
55         return name;
56     }
57 
58     @Override
59     public int doAfterBody() throws JspException {
60         if(iter.hasNext()){
61             super.pageContext.setAttribute(this.id,iter.next());
62             return TagSupport.EVAL_BODY_AGAIN; //反复执行
63         }else{
64             return TagSupport.SKIP_BODY;
65         }
66     }
67     @Override
68     public int doEndTag() throws JspException {
69         return super.doEndTag();
70     }
71     public void setName(String name) {
72         this.name = name;
73     }
74     public String getScope() {
75         return scope;
76     }
77     public void setScope(String scope) {
78         this.scope = scope;
79     }
80     public String getId() {
81         return id;
82     }
83     public void setId(String id) {
84         this.id = id;
85     }
86 }
View Code

MyBodyTag

 1 package test_servlet_package.tag;
 2 import java.io.IOException;
 3 import java.util.Iterator;
 4 import java.util.List;
 5 import javax.servlet.jsp.JspException;
 6 import javax.servlet.jsp.PageContext;
 7 import javax.servlet.jsp.tagext.BodyTagSupport;
 8 public class MyBodyTag extends BodyTagSupport{
 9     private static final long serialVersionUID = 1L;
10     private String name; //接受属性名称
11     private String scope; //接受查找范围
12     private String id;
13     private Iterator<?> iter = null;
14     @Override
15     public int doStartTag() throws JspException {
16         Object value = null;
17         if ("page".equals(this.scope)) {
18             value = super.pageContext.getAttribute(name, PageContext.PAGE_SCOPE); //是否是page范围
19         } else if ("request".equals(this.scope)) {    
20             value = super.pageContext.getAttribute(name,PageContext.REQUEST_SCOPE); //是否是request范围
21         } else if ("session".equals(this.scope)) {
22             value = super.pageContext.getAttribute(name,PageContext.SESSION_SCOPE); //是否是session范围
23         } else {
24             value = super.pageContext.getAttribute(name,PageContext.APPLICATION_SCOPE); //是否是application范围
25         }
26         if (value !=null && value instanceof List<?>) { //如果没有查到属性
27             this.iter = ((List<?>)value).iterator();
28             if(iter.hasNext()){
29                 super.pageContext.setAttribute(this.id,iter.next());
30                 return BodyTagSupport.EVAL_BODY_BUFFERED; //找到属性,执行标签题内容
31             }else{
32                 return BodyTagSupport.SKIP_BODY; //找到属性,执行标签题内容
33             }
34         }else{
35             return BodyTagSupport.SKIP_BODY; //不执行标签体内容
36         }
37     }
38     @Override
39     public int doAfterBody() throws JspException {
40         if(iter.hasNext()){
41             super.pageContext.setAttribute(this.id,iter.next());
42             return BodyTagSupport.EVAL_BODY_AGAIN; //反复执行
43         }else{
44             return BodyTagSupport.SKIP_BODY;
45         }
46     }
47     @Override
48     public int doEndTag() throws JspException { //这个 方法 不执行 则 没有 输出 
49         if(super.bodyContent != null){
50             try {
51                 super.bodyContent.writeOut(super.getPreviousOut());
52             } catch (IOException e) {
53                 e.printStackTrace();
54             }
55         }
56         return BodyTagSupport.EVAL_PAGE;
57     }
58     public String getName() {
59         return name;
60     }
61     public void setName(String name) {
62         this.name = name;
63     }
64     public String getScope() {
65         return scope;
66     }
67     public void setScope(String scope) {
68         this.scope = scope;
69     }
70     public String getId() {
71         return id;
72     }
73     public void setId(String id) {
74         this.id = id;
75     }
76 }
View Code
 1 package test_servlet_package.tag;
 2 import javax.servlet.jsp.tagext.TagData;
 3 import javax.servlet.jsp.tagext.TagExtraInfo;
 4 import javax.servlet.jsp.tagext.VariableInfo;
 5 public class MyTagExtraInfo extends TagExtraInfo{
 6     @Override
 7     public VariableInfo[] getVariableInfo(TagData data) {
 8         // TODO Auto-generated method stub
 9         return new  VariableInfo[]{ new VariableInfo(data.getId(),"java.lang.String",true,VariableInfo.NESTED)};
10     }
11 }
View Code

MySimpleTag

 1 package test_servlet_package.tag;
 2 import java.io.IOException;
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import javax.servlet.jsp.JspException;
 6 import javax.servlet.jsp.tagext.SimpleTagSupport;
 7 public class MySimpleTag extends SimpleTagSupport{
 8     //jsp 2.0 之后 的 出现  为了 简化 开发 
 9     private String format;
10     @Override
11     public void doTag() throws JspException, IOException {
12         SimpleDateFormat sdf = new SimpleDateFormat(this.format);
13         this.getJspContext().getOut().write(sdf.format(new Date()));
14     }
15     public String getFormat() {
16         return format;
17     }
18     public void setFormat(String format) {
19         this.format = format;
20     }
21 }
View Code

MySimpleTagForIter

 1 package test_servlet_package.tag;
 2 import java.io.IOException;
 3 import java.io.StringWriter;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 import javax.servlet.jsp.JspException;
 7 import javax.servlet.jsp.PageContext;
 8 import javax.servlet.jsp.tagext.JspFragment;
 9 import javax.servlet.jsp.tagext.SimpleTagSupport;
10 public class MySimpleTagForIter extends SimpleTagSupport{
11     //jsp 2.0 之后 的 出现  为了 简化 开发 
12     private String name; //接受属性名称
13     private String scope; //接受查找范围
14     private String id;
15     @Override
16     public void doTag() throws JspException, IOException {
17         Object value = null;
18         if ("page".equals(this.scope)) {
19             value = super.getJspContext().getAttribute(name, PageContext.PAGE_SCOPE); //是否是page范围
20         } else if ("request".equals(this.scope)) {
21             value = super.getJspContext().getAttribute(name,PageContext.REQUEST_SCOPE);//是否是request范围
22         } else if ("session".equals(this.scope)) {
23             value = super.getJspContext().getAttribute(name,PageContext.SESSION_SCOPE); //是否是session范围
24         } else {
25             value = super.getJspContext().getAttribute(name,PageContext.APPLICATION_SCOPE); //是否是application范围
26         }
27         if(value !=null && value instanceof List<?>){
28             Iterator iter = ((List<?>)value).iterator();
29             while(iter.hasNext()){
30                 super.getJspContext().setAttribute(this.id,iter.next());
31                 //PageContext pageContext = (PageContext) super.getJspBody().getJspContext();
32                 //super.getJspBody().invoke(pageContext.getOut());
33                 //super.getJspBody().invoke(null);//输出到相应里去 ,如果 是 个 流 文件 ,这会输出 到 文件 里去 ,,,
34                 JspFragment jf = this.getJspBody();
35                 StringWriter sw = new StringWriter();
36                 jf.invoke(sw);
37                 String s = sw.toString();
38                 s = "zczx";
39                 this.getJspContext().getOut().write(s); 
40             }
41         }
42     }
43     public String getName() {
44         return name;
45     }
46     public void setName(String name) {
47         this.name = name;
48     }
49     public String getScope() {
50         return scope;
51     }
52     public void setScope(String scope) {
53         this.scope = scope;
54     }
55     public String getId() {
56         return id;
57     }
58     public void setId(String id) {
59         this.id = id;
60     }
61 }
View Code

DynamicAttributesTag

 1 package test_servlet_package.tag;
 2 import java.io.IOException;
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 import java.util.Map;
 6 import javax.servlet.jsp.JspException;
 7 import javax.servlet.jsp.tagext.DynamicAttributes;
 8 import javax.servlet.jsp.tagext.SimpleTagSupport;
 9 
10 public class DynamicAttributesTag extends SimpleTagSupport implements DynamicAttributes {
11     // jsp 2.0 之后 的 出现 为了 简化 开发
12     private Map<String, Float> map = new HashMap<String, Float>();
13     @Override
14     public void doTag() throws JspException, IOException {
15         Float num = 0.0f;
16         Iterator<Map.Entry<String, Float>> iter = map.entrySet().iterator();
17         while (iter.hasNext()) {
18             Map.Entry<String, Float> val = iter.next();
19             num += val.getValue();
20         }
21         this.getJspContext().getOut().write(num + "");
22     }
23 
24     @Override
25     public void setDynamicAttribute(String arg0, String arg1, Object arg2) throws JspException {
26         map.put(arg1, Float.parseFloat(arg2.toString()));
27     }
28 }
View Code

测试

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ page import="java.util.*"%>
 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml"%>
 5 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
 6 <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
 7 <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
 8 <%@ taglib uri="kongxh_tag" prefix="mytag"%>
 9 <html>
10 <head>
11     <title>index.jsp</title>
12 </head>
13 <body>
14         <%
15             List<String> all = new ArrayList<String>();
16             all.add("test 1,");
17             all.add("test 2,");
18             all.add("test 3,");
19             request.setAttribute("all", all);
20         %>
21 
22     <mytag:IterTag name="all" scope="request" id="url">
23         ${url}
24     </mytag:IterTag>
25     <br/>
26     ----------------------
27     <mytag:MyBodyTag name="all" scope="request" id="url">
28         ${url}\ <%=url.length()%>
29     </mytag:MyBodyTag>
30     <br/>
31     ----------------------
32     <mytag:MySimpleTag format="yyyy-mm-dd" />
33     <br/>
34     ----------------------
35     <mytag:MySimpleTagForIter name="all" scope="request" id="url">
36         ${url}
37     </mytag:MySimpleTagForIter>
38     <br/>
39     ----------------------
40     <mytag:DynamicAttributesTag ab="3.4" gh="9.0" />
41     <br/>
42     ----------------------
43     <c:out value="Hello world"></c:out>
44 </body>
45 </html>
View Code

总结:复习和记录一下之前用到一个知识点。

posted on 2017-06-08 11:39  祥昊  阅读(228)  评论(0编辑  收藏  举报

导航