使用自定义标签重写JSTL核心标签库if标签

使用自定义标签重写JSTL核心标签库if标签


      • 使用自定义标签重写JSTL核心标签库if标签
        • 概述
        • 实现


概述


学习了自定义标签,并写了简单的测试demo之后,我决定要使用自定义标签实现JSTL核心标签库中的标签,选择了其中的三个标签进行重写,分别是:c:if c:choose+c:when+c:otherwise c:forEach,后续文章将按照自定义标签的开发方法进行重写。

实现


  • c:if 标签的开发代码
package com.jpzhutech.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

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 {
        System.out.println(test);
        if(test){
            //如果条件为真,则输出标签体的内容
            JspFragment jspBody = this.getJspBody();
            jspBody.invoke(null);
        }
    }
}


<taglib 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-jsptaglibrary_2_1.xsd"
    version="2.1">
    
  <tlib-version>1.1tlib-version>
  
  <short-name>jpzhutechshort-name>
  
  <uri>http://www.jpzhutech.comuri>

  <tag>
    
    <name>ShowIpname>
    
    <tag-class>com.jpzhutech.tag.ShowIptag-class>
    
    <body-content>scriptlessbody-content>
  tag>

  <tag>
    
    <name>ifname>
    
    <tag-class>com.jpzhutech.tag.IfTagtag-class>
    
    <body-content>scriptlessbody-content>

    <attribute>
        <name>testname>
        <required>truerequired>
        <rtexprvalue>truertexprvalue>
    attribute>
  tag>

  <tag>
    
    <name>demotagname>
    
    <tag-class>com.jpzhutech.tag.DemoTagtag-class>
    
    <body-content>scriptlessbody-content>

    <attribute>
        <name>namename>
        <required>truerequired>
        <fragment>truefragment>
    attribute>

    <attribute>
        <name>pricename>
        <required>truerequired>
        <fragment>truefragment>
    attribute>

    <attribute>
        <name>storename>
        <required>truerequired>
        <fragment>truefragment>
    attribute>

    <attribute>
        <name>countname>
        <required>truerequired>
        <fragment>truefragment>
    attribute>



  tag>
taglib>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.jpzhutech.com"  prefix="jpzhutech"%>


<html>
  <head>
    <title>自定义标签title>
  head>

  <body>
    <jpzhutech:ShowIp>你好jpzhutech:ShowIp>
    <jpzhutech:demotag name="Java编程思想" price="89.04" store="三味书屋" count="5">AAAA<br />jpzhutech:demotag>
    <jpzhutech:if test="${10 > 5}">
         条件成立
    jpzhutech:if>
  body>
html>

你可能感兴趣的:(Java)