自定义jsp标签进阶

简介: 自定义jsp标签进阶

前言

jsp自定义标签的优势

1.代码可重用性强:自定义标签将一部分的重复代码封装为一个标签,这些标签可以在不同的JSP页面上被重用,从而减少了代码重复的问题。

2. 代码可维护性好:自定义标签的改变只需在一个地方进行修改,就能够影响到所有使用该标签的页面,从而减少了代码维护的难度。

3.代码模块化:自定义标签具有逻辑上的独立性,可以方便地分离出一个功能模块,从而提高了代码的可读性和可维护性。

4.降低学习难度:利用自定义标签可以将较为复杂的功能封装起来,从而提高了开发人员的开发效率和降低了学习难度。

  1. 总之,自定义标签是JSP中一个非常强大的工具,可以大大简化JSP页面的开发和维护

1.自定义forech标签

1.定义助手类

package com.niyin.tag;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class foreachtag extends BodyTagSupport{
  private  List<Object> items=new ArrayList<Object>();
  //数据源,来遍历的
  private String var;
  public List<Object> getItems() {
    return items;
  }
  public void setItems(List<Object> items) {
    this.items = items;
  }
  public String getVar() {
    return var;
  }
  public void setVar(String var) {
    this.var = var;
  }
  @Override
  public int doAfterBody() throws JspException {
  Iterator<Object> it = (Iterator<Object>) pageContext.getAttribute("it");
    if (it.hasNext()) {
      pageContext.setAttribute(var,it.next() );
      pageContext.setAttribute("it", it);
      return EVAL_BODY_AGAIN;
    }
    return SKIP_BODY;
  }
  @Override
  public int doStartTag() throws JspException {
if (items==null|| items.size()==0) 
  return SKIP_BODY;
Iterator<Object> it = items.iterator();
pageContext.setAttribute(var,it.next() );
pageContext.setAttribute("it", it);
    return   EVAL_BODY_INCLUDE;
  }
}

2.写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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>http://jsp.niyin.cn</uri>
  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>
  <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>catch</name>
    <tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
 <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>foreach</name>
    <tag-class>com.niyin.tag.foreachtag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
 </taglib>

3.测试代码

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.niyin.entity.Dept"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://jsp.niyin.cn" prefix="z" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
List<Dept>list=new ArrayList();
 list.add(new Dept(1,"吊毛")); 
 list.add(new Dept(2,"好帅")); 
 list.add(new Dept(3,"真的帅")); 
request.setAttribute("list", list);
%>
 <%-- <c:forEach items="${list}" var="l">
${l.id }:${l.name}
</c:forEach> --%>
<z:foreach items="${list}" var="l">
${l.id }:${l.name}
</z:foreach> 
<z:dept var="li"></z:dept>
<%-- ${li } --%>
<%-- <z:select optiontext="name" items="${list }" optionVal="id"></z:select>
<z:select optiontext="name" items="${list }" optionVal="id" selectedVal="1"></z:select> --%>
</body>
</html>

运行结果

已经成功的定义了一个foreach标签。

2.dept标签

描述

dept用于封装数据让数据使用更为方便快捷

1.助手类

package com.niyin.tag;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.niyin.entity.Dept;
public class Depttag extends BodyTagSupport {
private String var ;//存放数据的名称
public String getVar() {
  return var;
}
public void setVar(String var) {
  this.var = var;
}
@Override
public int doStartTag() throws JspException {
//  pageContext.getOut();
  List<Dept>list=new ArrayList<Dept>();
   list.add(new Dept(1,"吊毛")); 
   list.add(new Dept(2,"好帅")); 
   list.add(new Dept(3,"真的帅")); 
   pageContext.setAttribute(var, list);
  return SKIP_BODY;
} 
}

2.编写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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>http://jsp.niyin.cn</uri>
  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>
  <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>catch</name>
    <tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
 <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>foreach</name>
    <tag-class>com.niyin.tag.foreachtag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
   <tag>
    <name>dept</name>
    <tag-class>com.niyin.tag.Depttag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <tag>
    <name>select</name>
    <tag-class>com.niyin.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
     <attribute>
        <name>optionVal</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>optiontext</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
 </taglib>

3.测试代码

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.niyin.entity.Dept"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://jsp.niyin.cn" prefix="z" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
List<Dept>list=new ArrayList();
 list.add(new Dept(1,"吊毛")); 
 list.add(new Dept(2,"好帅")); 
 list.add(new Dept(3,"真的帅")); 
request.setAttribute("list", list);
%>
 <%-- <c:forEach items="${list}" var="l">
${l.id }:${l.name}
</c:forEach> --%>
<%-- <z:foreach items="${list}" var="l">
${l.id }:${l.name}
 --%>
<%-- </z:foreach> 
 --%>
<z:dept var="li"></z:dept>
${li } 
<%-- <z:select optiontext="name" items="${list }" optionVal="id"></z:select>
<z:select optiontext="name" items="${list }" optionVal="id" selectedVal="1"></z:select> --%>
</body>
</html>

运行结果

3.自定义select标签

1.定义助手类

package com.niyin.tag;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class SelectTag extends BodyTagSupport {
  // 下拉框的数据源
  private List<Object> items = new ArrayList<Object>();
  private String optionVal;//id
  private String optiontext;//name
  private String selectedVal;//数据库中储存的数据,用于下拉框回显。
  public String getSelectedVal() {
    return selectedVal;
  }
  public void setSelectedVal(String selectedVal) {
    this.selectedVal = selectedVal;
  }
  public List<Object> getItems() {
    return items;
  }
  public void setItems(List<Object> items) {
    this.items = items;
  }
  public String getOptionVal() {
    return optionVal;
  }
  public void setOptionVal(String optionVal) {
    this.optionVal = optionVal;
  }
  public String getOptiontext() {
    return optiontext;
  }
  public void setOptiontext(String optiontext) {
    this.optiontext = optiontext;
  }
  @Override
  public int doStartTag() throws JspException {
    // 输出流
    JspWriter out = pageContext.getOut();
    try {
      out.print(toHTML());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return super.doStartTag();
  }
  private String toHTML() throws Exception {
    StringBuffer sb = new StringBuffer("<select>");
    for (Object object : items) {
      String val = getObjAttrValue(object, optionVal);
      String text = getObjAttrValue(object, optiontext);
      sb.append("<option "+(val.equals(selectedVal)?"selected":"")+" value='" + val + "'>" + text + "</option>");
      // sb.append(b)
    }
    sb.append("</select>");
    return sb.toString();
  }
  private String getObjAttrValue(Object object, String attr) throws Exception {
    Class clz = object.getClass();
    Field f = clz.getDeclaredField(attr);
    f.setAccessible(true);
    return f.get(object).toString();
  }
}

2.编写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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>http://jsp.niyin.cn</uri>
  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>
  <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>catch</name>
    <tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
 <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>foreach</name>
    <tag-class>com.niyin.tag.foreachtag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
   <tag>
    <name>dept</name>
    <tag-class>com.niyin.tag.Depttag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <tag>
    <name>select</name>
    <tag-class>com.niyin.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
     <attribute>
        <name>optionVal</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>optiontext</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
 </taglib>

3.测试代码

<?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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>http://jsp.niyin.cn</uri>
  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>
  <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>catch</name>
    <tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
 <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>foreach</name>
    <tag-class>com.niyin.tag.foreachtag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
        </description>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>
        </description>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
   <tag>
    <name>dept</name>
    <tag-class>com.niyin.tag.Depttag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <tag>
    <name>select</name>
    <tag-class>com.niyin.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
     <attribute>
        <name>optionVal</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>optiontext</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
 </taglib>

代码测试成功。

有什么问题请私信我。

目录
相关文章
|
6月前
|
SQL XML Java
JSP 教程 之 JSP 标准标签库(JSTL) 4
**JSP的JSTL是用于简化Web开发的标签库,包括核心、格式化、SQL、XML和函数5个部分。SQL标签库允许与数据库交互,如设定数据源、执行查询和更新,以及处理参数。例如, `&lt;sql:setDataSource&gt;` 定义数据源, `&lt;sql:query&gt;` 执行查询。通过使用JSTL,开发者能更整洁地处理JSP页面。**
52 8
|
6月前
|
XML SQL Java
JSP 教程 之 JSP 标准标签库(JSTL) 1
JSP的JSTL是用于简化页面逻辑的标签库,涵盖核心、格式化、SQL、XML和函数五大类标签。要安装,下载Apache的JSTL包,将jar文件放入WEB-INF/lib,tld文件复制到WEB-INF,并在web.xml中配置相应的taglib信息。JSTL促进了JSP页面的清洁和结构化。
49 5
|
6月前
|
缓存 安全 小程序
从基础到进阶:掌握Java中的Servlet和JSP开发
【6月更文挑战第23天】Java Web开发中的Servlet和JSP是关键技术,用于构建动态网站。Servlet是服务器端小程序,处理HTTP请求,生命周期包括初始化、服务和销毁。基础Servlet示例展示了如何响应GET请求并返回HTML。随着复杂性增加,JSP以嵌入式Java代码简化页面创建,最佳实践提倡将业务逻辑(Servlet)与视图(JSP)分离,遵循MVC模式。安全性和性能优化,如输入验证、HTTPS、会话管理和缓存,是成功应用的关键。本文提供了一个全面的学习指南,适合各级开发者提升技能。
52 7
|
6月前
|
XML SQL Java
JSP 教程 之 JSP 标准标签库(JSTL) 6
**JSP JSTL 摘要:** JSTL是JSP的标签库,包含核心、格式化、SQL、XML和函数5类标签。它用于执行常见任务,如迭代、条件判断和XML操作。JSTL函数库提供字符串处理函数,如`contains()`, `endsWith()`, `escapeXml()`等,方便XML和HTML处理。通过`&lt;%@ taglib %&gt;`导入,如`fn:trim()`用于去除字符串两端空白。
44 5
|
6月前
|
Java 应用服务中间件 Android开发
完成你的自定义JSP Tag标签-Basic Coustom Tag
完成你的自定义JSP Tag标签-Basic Coustom Tag
34 0
|
7月前
|
前端开发 Java 数据库
【Spring原理进阶】SpringMVC调用链+JSP模板应用讲解
【Spring原理进阶】SpringMVC调用链+JSP模板应用讲解
|
7月前
|
Java
jsp页面中使用jstl标签报错:javax.servlet.jsp.JspTagException
jsp页面中使用jstl标签报错:javax.servlet.jsp.JspTagException
106 0
|
Java
jsp标签下
jsp标签下
45 0
|
XML Java 数据格式
jsp标签上
jsp标签上
48 0
JSP标签(2) -----自定义foreach ,select标签,全网最详细,最完整易懂
JSP标签(2) -----自定义foreach ,select标签,全网最详细,最完整易懂