zoukankan      html  css  js  c++  java
  • jsp的标签库和自定义标签

    1.jstl标签库

    JSP标准标签库(JSTL)是一个JSP标签集合,它封装了JSP应用的通用核心功能。

    JSTL支持通用的、结构化的任务,比如迭代,条件判断,XML文档操作,国际化标签,SQL标签。 除了这些,它还提供了一个框架来使用集成JSTL的自定义标签。

    根据JSTL标签所提供的功能,可以将其分为5个类别。

    • 核心标签
    • 格式化标签
    • SQL 标签(过时)
    • XML 标签(过时)
    • JSTL 函数
    1.1使用taglib指令导入标签库 ,除了JSP动作标签外,使用其他第三方的标签库都需要:  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

    prefix="c":指定标签库的前缀,这个前缀可以随便给值,但大家都会在使用core标签库时指定前缀为c

    指定标签库的uri,它不一定是真实存在的网址,但它可以让JSP找到标签库的描述文件;

    outset标签:

    <c:out value=”aaa”/>                                                 输出aaa字符串常量

    <c:out value=”${aaa}”/>                                           与${aaa}相同

    <c:set var=”a” value=”hello”/>                                    pageContext中添加nameavaluehello的数据。

    <c:set var=”a” value=”hello” scope=”session”/>            session中添加nameavaluehello的数据。

    remove标签:

    <c:remove var="a"/>                                                  删除所有域中namea的数据

    <c:remove var="a" scope=”page”/>                              删除pageContextnamea的数据

    url标签:

    <c:url value="/"/>                                  输出上下文路径

    if标签:  test属性必须是一个boolean类型的值,如果test的值为true,那么执行if标签的内容,否则不执行。

    <c:set var="a" value="hello"/>

    <c:if test="${not empty a }">

    <c:out value="${a }"/>

    </c:if>

    choose标签: 对应Java中的if/else if/else结构。when标签的testtrue时,会执行这个when的内容。当所有when标签的test都为false时,才会执行otherwise标签的内容。

    <c:set var="score" value="${param.score }"/>

    <c:choose>

    <c:when test="${score > 100 || score < 0}">错误的分数:${score }</c:when>

    <c:when test="${score >= 80 }">A</c:when>

    <c:when test="${score >= 70 }">C</c:when>

    <c:when test="${score >= 60 }">D</c:when>

    <c:otherwise>E</c:otherwise>

    </c:choose>

    forEach标签:
       forEach当前就是循环标签了,forEach标签有多种两种使用方式:
       使用循环变量,指定开始和结束值,类似for(int i = 1; i <= 10; i++) {}
      循环遍历集合,类似for(Object o : 集合)

    循环变量方式:

    <c:set var="sum" value="0" />

    <c:forEach var="i" begin="1" end="10">

    <c:set var="sum" value="${sum + i}" />

    </c:forEach>

    <c:out value="sum = ${sum }"/>

    遍历集合或数组方式:

    <%

    String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};

    pageContext.setAttribute("ns", names);

    %>

    <c:forEach var="item" items="${ns }">

    <c:out value="name: ${item }"/><br/>

    </c:forEach>

    遍历map:

    <%

    Map<String,String> stu = new LinkedHashMap<String,String>();

    stu.put("number", "N_1001");

    stu.put("name", "zhangSan");

    stu.put("age", "23");

    stu.put("sex", "male");

    pageContext.setAttribute("stu", stu);

    %>

    <c:forEach var="item" items="${stu }">

    <c:out value="${item.key }: ${item.value }"/><br/>

    </c:forEach>

     1.2fmt标签库常用标签,需要导入包: <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

        fmt标签库是用来格式化输出的,通常需要格式化的有时间和数字。

     格式化时间:

    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

    ......

    <%

    Date date = new Date();

    pageContext.setAttribute("d", date);

    %>

    <fmt:formatDate value="${d }" pattern="yyyy-MM-dd HH:mm:ss"/>

    格式化数字:

    <%

    double d1 = 3.5;

    double d2 = 4.4;

    pageContext.setAttribute("d1", d1);

    pageContext.setAttribute("d2", d2);

    %>

    <fmt:formatNumber value="${d1 }" pattern="0.00"/><br/>

    <fmt:formatNumber value="${d2 }" pattern="#.##"/>

    2.jstl自定义标签

    2.1其实我们在JSP页面中使用标签就等于调用某个对象的某个方法一样,例如:<c:if test=””>,这就是在调用对象的方法一样。自定义标签其实就是自定义类一样!

    定义标签处理类:必须是TagSimpleTag的实现类;

    编写标签库描述符文件(TLD);

    SimpleTag接口是JSP2.0中新给出的接口,用来简化自定义标签,所以现在我们基本上都是使用SimpleTag

    2.2 SimpleTag接口介绍

    SimpleTag接口内容如下:

     void doTag():标签执行方法;

    JspTag getParent():获取父标签;

     void setParent(JspTag parent):设置父标签

    void setJspContext(JspContext context):设置PageContext

     void setJspBody(JspFragment jspBody):设置标签体对象;

    标签的生命周期:

    1. 当容器(Tomcat)第一次执行到某个标签时,会创建标签处理类的实例;
    2. 然后调用setJspContext(JspContext)方法,把当前JSP页面的pageContext对象传递给这个方法;
    3. 如果当前标签有父标签,那么使用父标签的标签处理类对象调用setParent(JspTag)方法;
    4. 如果标签有标签体,那么把标签体转换成JspFragment对象,然后调用setJspBody()方法;
    5. 每次执行标签时,都调用doTag()方法,它是标签处理方法。

    2.3例子

    public class HelloTag implements SimpleTag {
        private JspTag parent;
        private PageContext pageContext;
        private JspFragment jspBody;
        
        public void doTag() throws JspException, IOException {
            pageContext.getOut().print("Hello Tag!!!");[获取out对象,输出Hello Tag!!!]
        }
        public void setParent(JspTag parent) {
            this.parent = parent;
        }
        public JspTag getParent() {
            return this.parent;
        }
        public void setJspContext(JspContext pc) {
            this.pageContext = (PageContext) pc;
        }
        public void setJspBody(JspFragment jspBody) {
            this.jspBody = jspBody;
        }
    }

    标签库描述文件(TLD

    标签库描述文件是用来描述当前标签库中的标签的!标签库描述文件的扩展名为tld

    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xml="http://www.w3.org/XML/1998/namespace" 
        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 ">
    
        <tlib-version>1.0</tlib-version>[指定当前标签库的版本]
        <short-name>itcast</short-name>[指定当前标签库的简称,这个名称无所谓了,随便起。]
        <uri>http://www.wo.cn/tags</uri> [指定标签库的uri]
        <tag>  [部署一个标签!一个<tag>表示一个标签。]
            <name>hello</name>[指定标签的名称]
            <tag-class>cn.wo.tag.HelloTag</tag-class>[指定标签处理类]
            <body-content>empty</body-content>[指定标签体内容类型为空类型,即没有标签体。]
        </tag>
    </taglib>

    使用标签

    在页面中使用标签分为两步:

    使用taglib导入标签库;

    使用标签;

    <%@ taglib prefix="it" [指定标签库前缀]uri="/WEB-INF/hello.tld"[指定标签库的tld文件位置] %>
    ......
    <it:hello/>

    2.4 继承SimpleTagSuppport要比实现SimpleTag接口方便太多了,现在你只需要重写doTag()方法,其他方法都已经被SimpleTagSuppport完成了。

    public class HelloTag extends SimpleTagSupport {
        public void doTag() throws JspException, IOException {
            this.getJspContext().getOut().write("<p>Hello SimpleTag!</p>")//向页面输出;
        }
    }

    我们先来看看标签体内容的可选值:

    <body-content>元素的可选值有:

     empty:无标签体。

    JSP:传统标签支持它,SimpleTag已经不再支持使用<body-content>JSP</body-content>标签体内容可以是任何东西:ELJSTL<%=%><%%>,以及html

     scriptless:标签体内容不能是Java脚本,但可以是ELJSTL等。在SimpleTag中,如果需要有标签体,那么就使用该选项

     tagdependent:标签体内容不做运算,由标签处理类自行处理,无论标签体内容是ELJSPJSTL,都不会做运算。这个选项几乎没有人会使用!

    自定义有标签体的标签需要:

     获取标签体对象:JspFragment jspBody = getJspBody();

    把标签体内容输出到页面:jspBody.invoke(null)

     tld中指定标签内容类型:scriptless

    public class HelloTag extends SimpleTagSupport {
        public void doTag() throws JspException, IOException {
            PageContext pc = (PageContext) this.getJspContext();
            HttpServletRequest req = (HttpServletRequest) pc.getRequest();
            String s = req.getParameter("exec");
            if(s != null && s.endsWith("true")) {
                JspFragment body = this.getJspBody()//获取当前标签的标签体对象
                body.invoke(null);//向页面输出标签体内容
    } } }

    在dtd文件下添加以下代码 :

    <tag>
            <name>hello</name>
            <tag-class>tags.HelloTag</tag-class>//类路径
            <body-content>scriptless</body-content>//指定标签体内容为scriptless,即标签体内容可以是正常的html,也可以是EL或JSTL
        </tag>

    在jsp添加以下代码:

        <it:hello>
             <h1>哈哈哈~</h1>
        </it:hello>

    2.5 带有属性的标签

      一般标签都会带有属性,例如<c:if test=””>,其中test就是一个boolean类型的属性。完成带有属性的标签需要:

    在处理类中给出JavaBean属性(提供get/set方法);

    TLD中部属相关属性。

    public class IfTag extends SimpleTagSupport {
    
    private boolean test;
    
    public boolean isTest() {
    
    return test;
    
    }
    
    public void setTest(boolean test) {
    
    this.test = test;
    
    }
    
    @Override
    
    public void doTag() throws JspException, IOException {
    
    if(test) {
    
    this.getJspBody().invoke(null);
    
    }
    
    }
    
    }
    <tag> 
    
    <name>if</name> 
    
    <tag-class>tag.IfTag</tag-class> 
    
    <body-content>scriptless</body-content>
    
    <attribute>
    
    <name>test</name>
    
    <required>true</required>
    
    <rtexprvalue>true</rtexprvalue>
    
    </attribute> 
    
    </tag>
    <%
    
    pageContext.setAttribute("one", true);
    
    pageContext.setAttribute("two", false);
    
    %>
    
    <it:if test="${one }">xixi</it:if>
    
    <it:if test="${two }">haha</it:if>
    
    <it:if test="true">hehe</it:if>
     
     
  • 相关阅读:
    linux安装python3
    web模拟终端 --使用shellinabox
    linux防火墙和xshell的链接
    Linux安装在虚拟机上
    DRF(django-rest_framework)框架
    Pycharm常用快捷键
    普通脚本调用django程序
    Pycharm安装模块提示module 'pip' has no attribute 'main'的问题
    Django的ModelForm
    面向对象(常用和特殊的创建类)
  • 原文地址:https://www.cnblogs.com/y3596597/p/6827020.html
Copyright © 2011-2022 走看看