javaee学习之路(十六)JSP自定义标签

时间:2021-07-01 21:00:12

例1、使用自定义标签输出客户机的IP
第一步、1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '1.jsp' starting page</title>   
  </head>
  <body>
    您的ip是:
    <% String ip=request.getRemoteAddr(); out.print(ip); %>
  </body>
</html>

第二步、使用自定义标签。
Step1、定义类

package cn.itcast.web.tag;
import *;
public class ViewIPTag extends TagSupport{
    public int doStartTag() throws JspException {
        HttpServletRequest request=(HttpServletRequest)this.pageContext.getRequest();
        JspWriter out = this.pageContext.getOut();
        String ip=request.getRemoteAddr();
        try {
            out.print(ip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return super.doStartTag();
    }
}

Step2、在WEB-INF目录下面建立一个文件itcast.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>http://www.itcast.cn</uri>

    <tag>
         <name>viewIP</name>
        <tag-class>cn.itcast.web.tag.ViewIPTag</tag-class>
        <body-content>empty</body-content>
    </tag>

</taglib>

Step3、1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.cn" prefix="itcast"%> 
请注意上面的uri和prefix与tld文件的对应关系
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>自定义标签</title>   
  </head>
  <body> 
    您的ip是:<itcast:viewIP/>
  </body>
</html>

http://localhost:8080/day11/1.jsp
您的ip是:127.0.0.1
自定义标签入门:
1、 编写一个实现了tag接口的java类
2、 在tld文件中对标签处理器类进行描述(tld文件的位置:WEB-INF下面)
可以抄袭一下:C:\tomcat\webapps\examples\WEB-INF\jsp2 里面的tld文件,然后修改
3、在jsp页面中导入和使用自定义标签
上述程序的执行过程为见下图:
上述的1.jsp翻译后的Servlet为:

    ……
if (_jspx_meth_itcast_005fviewIP_005f0(_jspx_page_context))
        return;
……
private boolean _jspx_meth_itcast_005fviewIP_005f0(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  itcast:viewIP
                      cn.itcast.web.tag.ViewIPTag _jspx_th_itcast_005fviewIP_005f0 = (cn.itcast.web.tag.ViewIPTag) _005fjspx_005ftagPool_005fitcast_005fviewIP_005fnobody.get(cn.itcast.web.tag.ViewIPTag.class);
    _jspx_th_itcast_005fviewIP_005f0.setPageContext(_jspx_page_context);
    _jspx_th_itcast_005fviewIP_005f0.setParent(null);
    int _jspx_eval_itcast_005fviewIP_005f0 = _jspx_th_itcast_005fviewIP_005f0.doStartTag();
    if (_jspx_th_itcast_005fviewIP_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fitcast_005fviewIP_005fnobody.reuse(_jspx_th_itcast_005fviewIP_005f0);
      return true;
    }
    _005fjspx_005ftagPool_005fitcast_005fviewIP_005fnobody.reuse(_jspx_th_itcast_005fviewIP_005f0);
    return false;
  }

这里面没有调用release()而是将标签对象存入了内存,以供下次访问。
javaee学习之路(十六)JSP自定义标签

例2、自定义标签功能扩展之控制标签后的标签体是否执行
第一步、TagDemo1.java

package cn.itcast.web.tag;
import *;
public class TagDemo1 extends TagSupport {
    public int doStartTag() throws JspException {
        return Tag.SKIP_BODY; //标签体的内容不执行
        // return Tag.EVAL_BODY_INCLUDE; 标签体的内容执行!!!

    }
}

第二步、

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>http://www.itcast.cn</uri>

    <tag>
         <name>viewIP</name>
        <tag-class>cn.itcast.web.tag.ViewIPTag</tag-class>
        <body-content>empty</body-content>
    </tag>

    <tag>
         <name>demo1</name>
        <tag-class>cn.itcast.web.tag.TagDemo1</tag-class>
        <body-content>JSP</body-content>
       注意:上面一行中的JSP要大写!!!
    </tag>

</taglib>

第三步、2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.cn" prefix="itcast"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>使用标签控制页面内容是否输出</title>   
  </head>
  <body>
   <itcast:demo1>
    fandong123
    </itcast:demo1>
  </body>
</html>

例3、自定义标签功能扩展之控制整个JSP页面是否输出
第一步、TagDemo2.java

package cn.itcast.web.tag;
import *;
public class TagDemo2 extends TagSupport {
    public int doEndTag() throws JspException {
        //return Tag.SKIP_PAGE; 表示自定义标签后面的jsp内容不会执行
        return Tag.EVAL_PAGE; 表示自定义标签后面的jsp内容会执行
    }
}

第二步、itcast.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>http://www.itcast.cn</uri>

     <tag>
         <name>demo2</name>
        <tag-class>cn.itcast.web.tag.TagDemo2</tag-class>
        <body-content>empty</body-content>
    </tag>

</taglib>

第三步、3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.cn" prefix="itcast" %>
<itcast:demo2/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>控制整个JSP页面是否输出</title>   
  </head>
  <body>
    Fandong123 <br>
  </body>
</html>

例4、自定义标签功能扩展之控制JSP页面中某部分重复多次执行
第一步、TagDemo3.java

package cn.itcast.web.tag;
import *;
//控制标签体执行五次
public class TagDemo3 extends TagSupport {
   int x=5;
    public int doStartTag() throws JspException {
        return Tag.EVAL_BODY_INCLUDE;
    }

    public int doAfterBody() throws JspException {
        x--;
        if(x>0){
            return IterationTag.EVAL_BODY_AGAIN;
        }else{
            return IterationTag.SKIP_BODY;
        }
    }
}

第二步、itcast.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>http://www.itcast.cn</uri>

    <tag>
         <name>demo3</name>
        <tag-class>cn.itcast.web.tag.TagDemo3</tag-class>
        <body-content>JSP</body-content>
    </tag>
</taglib>

第三步、4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.cn" prefix="itcast" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '4.jsp' starting page</title>   
  </head>
  <body>
   <itcast:demo3>
    fandong <br>
    </itcast:demo3>
  </body>
</html>

输出结果为:
fandong
fandong
fandong
fandong
fandong
例5、自定义标签功能扩展之修改JSP页面中某部分内容并重新输出。
第一步、TagDemo4.java

package cn.itcast.web.tag;
import *;
//修改标签体(把标签体改为大写)
public class TagDemo4 extends BodyTagSupport {

    public int doStartTag() throws JspException {
        return BodyTag.EVAL_BODY_BUFFERED;
    }

    public int doEndTag() throws JspException {
        BodyContent bc = this.getBodyContent();//得到标签体
        String content = bc.getString();//注意不是toString();
        content = content.toUpperCase();
        try {
            this.pageContext.getOut().write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Tag.EVAL_PAGE;
    }
}

第二步、itcast.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>http://www.itcast.cn</uri>
    <tag>
         <name>demo4</name>
        <tag-class>cn.itcast.web.tag.TagDemo4</tag-class>
        <body-content>JSP</body-content>
    </tag>

</taglib>

第三步、5.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.cn" prefix="itcast" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用标签修改jsp页面内容</title>   
  </head>
  <body>
    <itcast:demo4>
      aaaaaaaaaaa
    </itcast:demo4>
  </body>
</html>

http://localhost:8080/day11/5.jsp
AAAAAAAAAAA
例6、用简单标签实现JSP页面部分内容输出。
第一步、SimpleDemo1.java

package cn.itcast.web.simpletag;
import*;
//控制标签体是否执行
public class SimpleDemo1 extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        JspFragment jf=this.getJspBody();
        jf.invoke(this.getJspContext().getOut());       
    }
}

第二步、simpleitcast.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>/simpletag</uri>
    <tag>
         <name>demo1</name>
        <tag-class>cn.itcast.web.simpletag.SimpleDemo1</tag-class>
        <body-content>scriptless</body-content>
    </tag>
</taglib>

第三步、1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/simpletag" prefix="sitcast"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用简单标签控制是否执行标签体</title>   
  </head>
  <body>
    <sitcast:demo1>
       fandong12388
    </sitcast:demo1>
  </body>
</html>

在IE中键入:http://localhost:8080/day11/simpletag/1.jsp
在WebRoot目录下面建立一个simpletag文件夹来存放1.jsp,所以访问路径为:
http://localhost:8080/day11/simpletag/1.jsp
结果将输出:fandong12388

例6、用简单标签实现JSP页面部分内容不输出。
只需将上面的第一步内容改为:

package cn.itcast.web.simpletag;
import*;
//控制标签体是否执行
public class SimpleDemo1 extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {

}

}即可
例6、用简单标签去迭代标签体。
第一步、SimpleDemo2.java

package cn.itcast.web.simpletag;
import *;
//控制标签体是否执行
public class SimpleDemo2 extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        JspFragment jf=this.getJspBody();
        for(int i=0;i<5;i++){
           jf.invoke(this.getJspContext().getOut());
           //上式等同于jf.invoke(null);
        }
    }
}

第二步、配置simpleitcast.tld
第三步、2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/simpletag" prefix="sitcast"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用简单标签去迭代标签体</title>   
  </head>
  <body>
    <sitcast:demo2>
       fandong12388
    </sitcast:demo2>
  </body>
</html>

例6、用简单标签去修改标签体。
第一步、SimpleDemo3.java

package cn.itcast.web.simpletag;
import *;
//控制标签体是否执行
public class SimpleDemo3 extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        JspFragment jf=this.getJspBody();
        StringWriter sw=new StringWriter();
        jf.invoke(sw);
        String content=sw.toString();
        content=content.toUpperCase();
        this.getJspContext().getOut().write(content);
    }
}

第二步、配置simpleitcast.tld
第三步、3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/simpletag" prefix="sitcast"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>修改标签体</title>   
  </head>
  <body>
    <sitcast:demo3>
       fandong12388
    </sitcast:demo3>
  </body>
</html>

http://localhost:8080/day11/simpletag/3.jsp
FANDONG12388

例7、控制标签余下的JSP不执行。—-向翻译后的Servlet抛一个SkipPageException()异常
第一步、SimpleDemo4.java

package cn.itcast.web.simpletag;
import *;
//控制标签余下的JSP不执行
public class SimpleDemo4 extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        throw new SkipPageException();
    }
}

第二步、配置simpleitcast.tld
第三步、4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/simpletag" prefix="sitcast"%>
<sitcast:demo4/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>控制整个JSP的输出</title>   
  </head>
  <body>
    <sitcast:demo3>
       fandong12388
    </sitcast:demo3>
  </body>
</html>

http://localhost:8080/day11/simpletag/4.jsp
查看网页的源代码,是一片空白的
例8、开发带属性的标签
第一步、SimpleDemo5.java

package cn.itcast.web.simpletag;
import *;
public class SimpleDemo5 extends SimpleTagSupport {
    private int count;//第一步获取属性名称
    public void setCount(int count) {//第二步获得属性的set方法
        this.count = count;
    }
    public void doTag() throws JspException, IOException {//第三步利用属性(值)进行操作
        JspFragment jf=this.getJspBody();
        for(int i=0;i<count;i++){
            jf.invoke(null);
        }
    }
}

第二步、

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>/simpletag</uri>
    <tag>
         <name>demo5</name>
        <tag-class>cn.itcast.web.simpletag.SimpleDemo5</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
           <name>count</name>
           <required>true</required>//该属性是否是必须的?true;false;yes;no
 <rtexprvalue>true</rtexprvalue>//运行时表达式的值,true表示可以再JSP页面给count属性//用表达式赋值(包括EL表达式等等),false表示只能用这样的形式赋值:count=”9”
        </attribute>
    </tag>
</taglib>

第三步、5.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/simpletag" prefix="sitcast"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>开发带属性的标签</title>   
  </head>
  <body>
    <sitcast:demo5 count="9">
       fandong12388<br/>
    </sitcast:demo5>
  </body>
</html>

http://localhost:8080/day11/simpletag/5.jsp
结果为:
fandong12388
fandong12388
fandong12388
fandong12388
fandong12388
fandong12388
fandong12388
fandong12388
fandong12388
例9、标签案例-开发防盗链标签
第一步、RefererTag.java

package cn.itcast.web.tag.example;
import java.io.IOException;
import *;
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;
    }
    public void doTag() throws JspException, IOException {
        PageContext pageContext=(PageContext)this.getJspContext();
        HttpServletRequest request=(HttpServletRequest) pageContext.getRequest();
        HttpServletResponse response=(HttpServletResponse) pageContext.getResponse();
        //1.得到来访者referer
        String referer=request.getHeader("referer");
        if(referer==null || !referer.startsWith(site)){
            if(page.startsWith(request.getContextPath())){
                response.sendRedirect(page);

            }else if(page.startsWith("/")){
                response.sendRedirect(request.getContextPath()+page);

            }else {
                response.sendRedirect(request.getContextPath()+"/"+page);
            }
            throw new SkipPageException();
        }else{

        }
        //2.判断来访者的页面是不是要防盗链
    }
}

第二步、example.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>itcast</short-name>
    <uri>/example</uri>
    <tag>
         <name>referer</name>
        <tag-class>cn.itcast.web.tag.example.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>
</taglib>

第三步、1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/example" prefix="fix"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<fix:referer site="http://localhost" page="/index.jsp"/>
<%--针对site网站防盗链,如果不是从该网站来的就是盗链,就跳转到page指定的页面显示 --%>
<html>
  <head>
    <title>My JSP '1.jsp' starting page</title>   
  </head>
  <body>
    凤姐XXXXXXXXXXXXXXXXXXXXXXXX凤姐!<br>
  </body>
</html>

第四步、index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
    This is my JSP page. <br>
    <a href="${pageContext.request.contextPath}/example/1.jsp">凤姐日记</a>
  </body>
</html>

第五步、测试:如果直接键入:
http://localhost:8080/day11/example/1.jsp 是不能访问1.jsp的,会跳转到index.jsp ,如果点击首页上面的超链接,则可以访问到1.jsp(前者的referer头为空)
例10.标签案例-开发<c:if>标签
第一步、IfTag.java

package cn.itcast.web.tag.example;
import *;
public class IfTag extends SimpleTagSupport {
    private boolean test;
    public void setTest(boolean test) {
        this.test = test;
    }
    public void doTag() throws JspException, IOException {
        if(test){
            this.getJspBody().invoke(null);
        }
    }
}

第二步、example.tld

 <tag>
         <name>if</name>
        <tag-class>cn.itcast.web.tag.example.IfTag</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
           <name>test</name>
           <required>true</required>
           <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>

第三步、2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/example" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '2.jsp' starting page</title>   
  </head>
  <body>
    <c:if test="${user==null }"> 
        aaaaaaaaaaaaaa<br/>
    </c:if>
    <c:if test="${user!=null}">
         Bbbbbbbbbbbb<br/>
    </c:if>
  </body>
</html>

第四步、在IE中键入http://localhost:8080/day11/example/2.jsp,可以看到打印出
aaaaaaaaaaaaaa
第五步、在标签对之间加入

<%
     session.setAttribute("user","aaa");
 %>

并在IE中键入:http://localhost:8080/day11/example/2.jsp
结果为:Bbbbbbbbbbbb

例11.标签案例-开发if.else标签(即when,otherwise标签开发)
第一步、3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/example" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '3.jsp' starting page</title>   
  </head>
  <body>
  <c:choose>
    <c:when test="${user!=null}">
       aaaaaaa
    </c:when>
    <c:otherwise>
         bbbbbbbb
     </c:otherwise>
     </c:choose>
  </body>
</html>

第二步、ChooseTag.java

package cn.itcast.web.tag.example;
import *;
public class ChooseTag extends SimpleTagSupport {
    private boolean isDo;
    public boolean isDo() {//相当于get方法,is开头的很特殊
        return isDo;
    }
    public void setDo(boolean isDo) {//相当于set方法
        this.isDo = isDo;
    }
    public void doTag() throws JspException, IOException {
        this.getJspBody().invoke(null);
    }
}

第三步、WhenTag.java

package cn.itcast.web.tag.example;
import *;
public class WhenTag extends SimpleTagSupport {
    private boolean test;

    public void setTest(boolean test) {
        this.test = test;
    }

    public void doTag() throws JspException, IOException {
        ChooseTag parent= (ChooseTag)this.getParent();
        if(test && !parent.isDo()){
            this.getJspBody().invoke(null);
            parent.setDo(true);
        }
    }
}

第四步、OtherWiseTag.java

package cn.itcast.web.tag.example;
import *;
public class OtherWiseTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        ChooseTag parent = (ChooseTag)this.getParent();
        if(!parent.isDo()){
            this.getJspBody().invoke(null);
            parent.setDo(true);
        }
    }
}

第五步、example.tld

  <tag>
         <name>choose</name>
        <tag-class>cn.itcast.web.tag.example.ChooseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>
    <tag>
         <name>when</name>
        <tag-class>cn.itcast.web.tag.example.WhenTag</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
           <name>test</name>
           <required>true</required>
           <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
    <tag>
         <name>otherwise</name>
        <tag-class>cn.itcast.web.tag.example.OtherWiseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>

第六步、在IE中键入: http://localhost:8080/day11/example/3.jsp
会出现: aaaaaaa
如果在3.jsp中加入:

<%
     session.setAttribute("user","aaa");
 %>

显示结果将是:bbbbbbbb
例12.标签案例-开发迭代标签上(初级)
第一步、4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/example" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '4.jsp' starting page</title>   
  </head>
  <body>
    <% List list=new ArrayList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); list.add("ddd"); request.setAttribute("list",list); %>
     <c:foreach var="str" items="${list }">
       ${str}
     </c:foreach>
  </body>
</html>

第二步、ForEachTag.java

public class ForEachTag extends SimpleTagSupport {
    private Object items;
    private String var;//注意这里是String
    public void setItems(Object items) {
        this.items = items;
    }
    public void setVar(String var) {
        this.var = var;
    }
    public void doTag() throws JspException, IOException {
        List list = (List)items;
        Iterator it=list.iterator();
        while(it.hasNext()){
            Object value=it.next();
            this.getJspContext().setAttribute(var, value);
            this.getJspBody().invoke(null);
        }
    }
}

第三步、example.tld

<tag>
         <name>foreach</name>
        <tag-class>cn.itcast.web.tag.example.ForEachTag</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>false</rtexprvalue>
        </attribute>
    </tag>

第四步、在IE中键入:
http://localhost:8080/day11/example/4.jsp
可以得到如下结果:aaa bbb ccc ddd
例13.标签案例-开发迭代标签下(高级)
第一步、5.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/example" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '4.jsp' starting page</title>   
  </head>
  <body>
  <% List list=new ArrayList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); list.add("ddd"); request.setAttribute("list",list); %>
     <c:foreach2 var="str" items="${list }">
       ${str}
     </c:foreach2>
      <br/>----------------------------------------------------------------<br/>
     <% Map map=new HashMap(); map.put("aa","11"); map.put("bb","22"); map.put("cc","33"); map.put("dd","44"); request.setAttribute("map",map); %>
      <c:foreach2 var="entry" items="${map }">
       ${entry.key} = ${entry.value }
     </c:foreach2>
    <br/>----------------------------------------------------------------<br/>
     <% Integer num[]={new Integer(1),new Integer(2),new Integer(3),new Integer(4)}; request.setAttribute("num",num); %>
      <c:foreach2 var="i" items="${num }">
       ${i}
     </c:foreach2>
     <br/>----------------------------------------------------------------<br/>
      <% int arr[]={1,2,3,4}; request.setAttribute("arr",arr); %>
      <c:foreach2 var="j" items="${arr }">
       ${j}
     </c:foreach2>
     <br/>----------------------------------------------------------------<br/>
         <% boolean b[]={true,false,true,false}; request.setAttribute("b",b); %>
      <c:foreach2 var="j" items="${b }">
       ${j}
     </c:foreach2> 
     <br/>----------------------------------------------------------------<br/>
 </body>
</html>

第二步、ForeachTag2.java

package cn.itcast.web.tag.example;
import *;
//ctrl+F表示在当前文档查找关键字
public class ForeachTag2 extends SimpleTagSupport {
    private Object items;
    private String var;
    private Collection collection;
    public void setItems(Object items) {
        this.items = items;
        if(items instanceof Collection){
            collection=(Collection)items;
        }
        if(items instanceof Map){
            Map map=(Map)items;
            collection=(map.entrySet());
        }
        //注意下面这段代码,在java里面可以对任意数组进行操作,很重要
        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;
    }
    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);
        }
    }
}

第三步、example.tld

<tag>
         <name>foreach2</name>
        <tag-class>cn.itcast.web.tag.example.ForeachTag2</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>false</rtexprvalue>
        </attribute>
    </tag>

第四步、在IE中键入:
http://localhost:8080/day11/example/4.jsp
可以得到如下结果:

aaa bbb ccc ddd ----------------------------------------------------------------
dd = 44 aa = 11 bb = 22 cc = 33 ----------------------------------------------------------------
1 2 3 4 ----------------------------------------------------------------
1 2 3 4 ----------------------------------------------------------------
true false true false ----------------------------------------------------------------

例14.标签案例-开发html转义标签。
第一步、6.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/example" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '6.jsp' starting page</title>   
  </head>
  <body>
   <c:htmlfilter>
    <a href="">点点</a>
    </c:htmlfilter>
  </body>
</html>

第二步、

package cn.itcast.web.tag.example;
import *;
public class HtmlFilterTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        StringWriter sw=new StringWriter();
        JspFragment jf = this.getJspBody();
        jf.invoke(sw);
        String content = sw.getBuffer().toString();
        content = filter(content);
        this.getJspContext().getOut().write(content);
    }
    public static String filter(String message) {
        if (message == null)
            return (null);
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
    }
}

第三步、example.tld

<tag>
         <name>htmlfilter</name>
        <tag-class>cn.itcast.web.tag.example.HtmlFilterTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>

第四步、在IE中键入:http://localhost:8080/day11/example/6.jsp
可以得到结果:<a href="">点点</a>
例15.将以上的自定义标签打包成jar。
第一步、在MyEclipse当中新建一个java Project,命名为example!
第二步、将名为day11的java web project的cn.itcast.web.tag.example包拷贝到example java工程的src 的文件夹当中(报错没关系)!
第三步、在example下面新建一个文件夹,命名为:META-INF用来存放配置文件,这里即是.tld文件,将day11中的example.tld文件拷贝到这里来!
第四步、在example工程名上点击右键,选择ExportJavaJAR fileNext将右边的.classpath和.priject取消选择,因为这两项是eclipse的配置选项Next选择输出的目录和输出的文件名,例如:C:\Documents and Settings\Administrator\桌面\itcast.jar->finish
第五步、如何使用 itcast.jar?
将itcast.jar复制粘贴到一个工程的WebRoot->WEB-INF->lib文件夹当中,然后在JSP页面当中导包:

<%@taglib uri=”/example” prefix=”itcast”% >

这样就能使用了,例如:<itcast:foreach></itcast:foreach>

例16.测试jstl标签库中的各类标签的使用方法。
第一步、导包,jstl-1.2.jar standard.jar 到lib目录下面
第二步、在webroot目录下面建立一个文件夹jstl,并在其中建立1.jsp

<%@ page language="java" import="java.util.*,cn.itcast.domain.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>测试jstl中的c:out</title>   
  </head>
  <body>
  <br/>--------------------------c:out-------------------------------<br/>
  <% request.setAttribute("data","<a href='"+request.getContextPath()+"/index.jsp'>点点</a>"); %>
    <c:out value="${data}" default="fandong" escapeXml="false"></c:out>
  <br/>------------c:set可以操作各个域 javabean Map集合---------------<br/>
  <c:set var="data" value="xxx" scope="page"/>
  ${data}

  <% Map map=new HashMap(); request.setAttribute("map",map); %>
   <c:set property="dd" value="fandong" target="${map}"/>
   ${map.dd}

   <% Person p=new Person(); request.setAttribute("p",p); %>
    <c:set property="name" value="uuuuu" target="${p}"/>
    ${p.name}
    <br/>--------------------------c:catch------------------------<br/>
    <c:catch var="myex">
    <% int x=1/0; %>
     </c:catch>
     ${myex.message}
<%--如何得知上面的代表一场对象的关键字myex有属性message?从Exception类中的getMessage()方法知道的 --%>
     <br/>--------------------------c:if------------------------<br/>
      <c:if var="aaa" test="${user==null}" scope="page">
        aaaaaa
       </c:if>
       ${aaa}
     <br/>--------------------------c:forEach-------------------<br/>
    <% List list=new ArrayList(); list.add("aaaa"); list.add("bbbb"); list.add("cccc"); list.add("dddd"); request.setAttribute("list",list); %>
     <c:forEach var="str" items="${list}">
        ${str}
     </c:forEach>
      <br/>------------------------------------------------------<br/>
      <c:forEach var="num" begin="1" end="9" step="1">
       ${num}
      </c:forEach>
      <br/>--------c:forEach实现表格间色显示-------------------<br/>
      <% list=new ArrayList(); list.add("aaaa"); list.add("bbbb"); list.add("cccc"); list.add("dddd"); list.add("eeee"); list.add("ffff"); list.add("gggg"); list.add("hhhh"); list.add("iiii"); request.setAttribute("list",list); %>
     <style> .odd{background: yellowgreen;} .even{background: #FF0000;} td:hover{background: #0000FF;} <%--上面一行表示鼠标移上去的那一行变为蓝色,注意:要将次文档声明为XHTML文档,可以打开http://localhost:8080的源文件来抄声明部分 --%> </style>
     <table border="1" width="35%">
       <c:forEach var="str" items="${list}" varStatus="status">
           <tr class="${status.count%2==0? 'even':'odd' }">
              <%--${status}获取到了一个对象,这个对象记住了当前是第几次迭代! --%>
               <td>${str}</td>
           </tr>
       </c:forEach>
     </table>
   <br/>--------------------c:url标签----------------------<br/>
   <c:url var="url" value="/day11/xx">
     <c:param name="name" value="中国"/>
    </c:url>
     <%--附带了一个名为name的参数,这里的中文会自动进行url编码 --%>
   <a href="${url}">购买</a>

   <%-- 此时打开IE浏览器,查看本网页的源代码,可以看到以下内容 <a href="/day11/day11/xx;jsessionid=D424A308F9D0F4EF8E77C3B71D3039EC">购买</a> 如果刷新网页,就没有jsessionid了,因为,刷新过后的网页请求中就有session对象了,不用另外创建 --%>

    <a href='<c:url value="/index.jsp"/>'>点点</a>
    <%--上面c:url标会为/index.jsp 自动加上web应用的名称,即/day11,注意三种取得web应用的方法--%>
<%--<c:url value="/index.jsp"/>不能单独使用,要用var不然就会将value中的内容加上web应用名输出到网页中 --%>

  <br/>-----------------c:forTokens标签(分割)------------------<br/>
 <% pageContext.setAttribute("data1","aa,bb,cc,dd"); %>
  <c:forTokens var="ss" items="${data1}" delims=",">
     ${ss}
  </c:forTokens>
  </body>
</html>

第三步、在IE中键入:http://localhost:8080/day11/jstl/1.jsp 可以看到如下结果:

<a href=''>点点</a>

第四步、将1.jsp修改为如下形式

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>测试jstl中的c:out</title>   
  </head>
  <body>
  <% request.setAttribute("data","<a href='"+request.getContextPath()+"/index.jsp'>点点</a>"); %>
    <c:out value="${data}" default="fandong" escapeXml="false"></c:out>
  </body>
</html>

在IE中键入:http://localhost:8080/day11/jstl/1.jsp 可以看到如下结果:

javaee学习之路(十六)JSP自定义标签