Jstl自定义标签及其生命周期、属性标签、及其读取文本练习、JspFragment输出标签体(2)

本文主要是介绍Jstl自定义标签及其生命周期、属性标签、及其读取文本练习、JspFragment输出标签体(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

什么是自定义标签?
标签处理器可以做哪些操作呢?
属性标签
输出一个文件-利用自定义标签
利用JspFragment输出标签体的自定义标签

什么是自定义标签?
这里写图片描述

这里写图片描述

SimlpeTagSuPPort类的生命周期:
1.当jsp容器遇到自定义标签时。jsp容器会调用标签处理类的默认构造方法来建立一个标签处理类的实例。必须为每个标签都创建一个新的实例。
2.实例创建后,jsp容器会调用setJspContext()方法。并以一个JspContext实例提供上下文信息。如果是一个嵌套标签,还讲调用setParent()方法。
3.然后容器会调用该标签中所定义的每个属性的set方法,这样标签处理类实例就已经初始化完成了。
4.接着就由容器调用setJspBody()方法。将该标签的主题设置为JspFragment实例。如果标签主题是空的,则将null值传到setJspBody().JspFragment实例代表标签主题片段的引用。
5.接下来,由容器调用doTag()方法标签要实现的所有逻辑、循环、主体赋值等都在该方法中发生。
6.在doTag()方法返回后,标签处理类中所有的变量都是同步的。

如何创建自定义标签?
1、写一个标签处理类,实现SimpleTag接口方法
2、建议在WEB-INF下配置文件tld文件
3、在jsp中taglib导入标签库描述文件,使用即可

HelloSimpleTag

package com.safly;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;
public class HelloSimpleTag implements SimpleTag {public void doTag() throws JspException, IOException {System.out.println("doTag");}public JspTag getParent() {System.out.println("getParent");return null;}public void setJspBody(JspFragment jspBody) {System.out.println("setJspBody");}public void setJspContext(JspContext pc) {System.out.println("setJspContext");}public void setParent(JspTag parent) {System.out.println("setParent");}
}

mytld.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>MyTag 1.0 core library</description><display-name>MyTag core</display-name><tlib-version>1.0</tlib-version><short-name>safly</short-name><uri>http://www.safly.com/mytld/core</uri><tag><name>hello</name><tag-class>com.safly.HelloSimpleTag</tag-class><body-content>empty</body-content></tag>
</taglib>

mytag.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="http://www.safly.com/mytld/core" prefix="safly"%>
<html><body><!-- //prefix可用其他,但是<safly:hello/>相对应 --><safly:hello/> </body>
</html>

这里写图片描述

标签处理器可以做哪些操作呢?
通过jsp引擎调用,把代表jsp页面的pageContext对象传入,由于pageContext可以获取jsp页面其他的8个隐含对象,所以凡是jsp页面可以做的,标签处理器都可以做

还是上例中mytld.tld、mytag.jsp不过变化
HelloSimpleTag 做如下修改

package com.safly;
import java.io.IOException;import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;public class HelloSimpleTag implements SimpleTag {// 标签体逻辑实际编写到该方法中public void doTag() throws JspException, IOException {System.out.println("doTag");pageContext.getOut().println("helloworld");HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();pageContext.getOut().print("Hello" + request.getParameter("name"));}public JspTag getParent() {System.out.println("getParent");return null;}public void setJspBody(JspFragment jspBody) {System.out.println("setJspBody");}private PageContext pageContext;// jsp引擎调用,把代表jsp页面的pagecontext对象传入public void setJspContext(JspContext pc) {System.out.println("setJspContext");System.out.println(pc instanceof PageContext);this.pageContext = (PageContext) pc;}public void setParent(JspTag parent) {System.out.println("setParent");}}

这里写图片描述

属性标签
1.先在标签处理类中定义setter方法,建议属性都设置为String类型
2.在tld文件中来描述属性

mytld.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>MyTag 1.0 core library</description><display-name>MyTag core</display-name><tlib-version>1.0</tlib-version><short-name>safly</short-name><uri>http://www.safly.com/mytag/core</uri><tag><name>hello</name><tag-class>com.safly.HelloSimpleTag</tag-class><body-content>empty</body-content><attribute><name>value</name><required>true</required><!-- 当前属性是否可以接受运行时表达式的动态值 --><rtexprvalue>true</rtexprvalue></attribute><attribute><name>count</name><required>true</required><!-- 当前属性不可以接受运行时表达式的动态值 --><rtexprvalue>false</rtexprvalue></attribute></tag>
</taglib>

mytag.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="http://www.safly.com/mytag/core" prefix="safly"%>
<html><body><safly:hello value="${param.name}" count="5"/> </body>
</html>

HelloSimpleTag

package com.safly;
import java.io.IOException;import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;
public class HelloSimpleTag implements SimpleTag {
//建议把所有的属性定义成String类型private String value;private String count;public void setValue(String value) {this.value = value;}public void setCount(String count) {this.count = count;}// 标签体逻辑实际编写到该方法中public void doTag() throws JspException, IOException {System.out.println("doTag");JspWriter out = pageContext.getOut();int c = 0;c = Integer.parseInt(count);for (int i = 0; i < c; i++) {out.print(i + ":" + value);out.print("<br>");}}public JspTag getParent() {System.out.println("getParent");return null;}public void setJspBody(JspFragment jspBody) {System.out.println("setJspBody");}private PageContext pageContext;// jsp引擎调用,把代表jsp页面的pagecontext对象传入public void setJspContext(JspContext pc) {System.out.println("setJspContext");System.out.println(pc instanceof PageContext);this.pageContext = (PageContext) pc;}public void setParent(JspTag parent) {System.out.println("setParent");}
}

这里写图片描述

输出一个文件-利用自定义标签

mytld.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>MyTag 1.0 core library</description><display-name>MyTag core</display-name><tlib-version>1.0</tlib-version><short-name>safly</short-name><uri>http://www.safly.com/mytag/core</uri><tag><name>readerFile</name><tag-class>com.safly.ReadFileTag</tag-class><body-content>empty</body-content><attribute><name>src</name><required>true</required><!-- 当前属性是否可以接受运行时表达式的动态值 --><rtexprvalue>true</rtexprvalue></attribute></tag>
</taglib>

mytag.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="http://www.safly.com/mytag/core" prefix="safly"%>
<html><body><safly:readerFile src="/WEB-INF/abc.txt"/> </body>
</html>

ReadFileTag

package com.safly;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;public class ReadFileTag extends SimpleTagSupport {private String src;public void setSrc(String src){this.src = src;}@Overridepublic void doTag() throws JspException, IOException {super.doTag();PageContext pageContext = (PageContext) getJspContext();InputStream in = pageContext.getServletContext().getResourceAsStream(src);BufferedReader reader = new BufferedReader(new InputStreamReader(in) );String str = null;while ((str=reader.readLine())!=null) {pageContext.getOut().write(str);pageContext.getOut().write("<br>");}}
}

看下目录结构:
这里写图片描述

浏览器输出结果如下:
这里写图片描述

利用JspFragment输出标签体的自定义标签

 public void setJspBody(JspFragment jspBody) {System.out.println("setJspBody");}

它的实例对象代表JSP页面中的一段符合JSP语法规范的JSP片段

WEB容器在处理简单标签的标签体时,会把标签体内容用一个JspFragment对象表示,并调用标签处理器对象的setJspBody方法把JspFragment对象传递给标签处理器对象。JspFragment类中只定义了两个方法,如下所示:

getJspContext方法用于返回代表调用页面的JspContext对象.

public abstract voidinvoke(java.io.Writer out)

用于执行JspFragment对象所代表的JSP代码片段,参数out用于指定将JspFragment对象的执行结果写入到哪个输出流对象中,如果传递给参数out的值为null,则将执行结果写入到JspContext.getOut()方法返回的输出流对象中。(简而言之,可以理解为写给浏览器)

mytld.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>MyTag 1.0 core library</description><display-name>MyTag core</display-name><tlib-version>1.0</tlib-version><short-name>safly</short-name><uri>http://www.safly.com/mytag/core</uri><tag><name>testJspFragment</name><tag-class>com.safly.ReadFileTag</tag-class><body-content>scriptless</body-content></tag>
</taglib>

mytag.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="http://www.safly.com/mytag/core" prefix="safly"%>
<html><body><safly:testJspFragment>HelloWorld</safly:testJspFragment></body>
</html>

ReadFileTag

package com.safly;
import java.io.IOException;
import java.io.StringWriter;import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;public class ReadFileTag extends SimpleTagSupport {@Overridepublic void doTag() throws JspException, IOException {//自己定义的方法getJspBodyJspFragment bodyContent= getJspBody();//参数为字符流,若为null则输出getJspContext().getOut()到页面上StringWriter sw = new StringWriter();bodyContent.invoke(sw);String content = sw.toString().toUpperCase();getJspContext().getOut().print(content);}
}

这里写图片描述

带标签体的自定义标签练习
mytld.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>MyTag 1.0 core library</description><display-name>MyTag core</display-name><tlib-version>1.0</tlib-version><short-name>safly</short-name><uri>http://www.safly.com/mytag/core</uri><tag><name>printUpper</name><tag-class>com.safly.PrintUpperTag</tag-class><body-content>scriptless</body-content><attribute><name>time</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag><tag><name>forEach</name><tag-class>com.safly.PrintUpperTag</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>true</rtexprvalue></attribute></tag> 
</taglib>

Customer

package com.safly;public class Customer {private Integer id;private String name;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Customer(Integer id, String name) {super();this.id = id;this.name = name;}public Customer() {// TODO Auto-generated constructor stub}}

PrintUpperTag

package com.safly;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;public class PrintUpperTag extends SimpleTagSupport {private String time;public void setTime(String time) {this.time = time;}private Collection<?>items;private String var;public void setItems(Collection<?> items) {this.items = items;}public void setVar(String var) {this.var = var;}/@Overridepublic void doTag() throws JspException, IOException {JspFragment bodyContent = getJspBody();StringWriter sw = new StringWriter();bodyContent.invoke(sw);String content = sw.toString();content = content.toUpperCase();int count = 1;try {count = Integer.parseInt(time);} catch (Exception e) {}for (int i = 0; i < count; i++) {getJspContext().getOut().print(content+"<br>");}if (items!=null) {for (Object obj: items) {getJspContext().setAttribute(var, obj);getJspBody().invoke(null);}}}
}

mytag.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@page import="com.safly.Customer"%>
<%@taglib uri="http://www.safly.com/mytag/core" prefix="safly"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><body><safly:printUpper time="5">&nbsp;hello</safly:printUpper><%List<Customer> customers = new ArrayList<Customer>();customers.add(new Customer(1,"AAA"));customers.add(new Customer(2,"BBB"));customers.add(new Customer(3,"CCC"));request.setAttribute("customers",customers);Map<String,Customer> customerMap = new HashMap<String,Customer>();customerMap.put("a",customers.get(0));customerMap.put("b",customers.get(1));customerMap.put("c",customers.get(2));request.setAttribute("customerMap",customerMap);    %><c:forEach items="${customerMap }" var ="cust">${pageScope.cust.key }--${cust.value.id }---${cust.value.name }</c:forEach><safly:forEach items="${customers }" var ="cust">${pageScope.cust.id }--${cust.name }</safly:forEach> </body>
</html>

浏览器输入http://localhost:8080/day01/mytag.jsp
输出结果如下:

&NBSP;HELLO
&NBSP;HELLO
&NBSP;HELLO
&NBSP;HELLO
&NBSP;HELLO
b--2---BBB c--3---CCC a--1---AAA -- 
1--AAA 2--BBB 3--CCC 

主要来说下

 <safly:forEach items="${customers }" var ="cust">${pageScope.cust.id }--${cust.name }</safly:forEach> 

如果传递给参数out的值为null,则将执行结果写入到JspContext.getOut()方法返回的输出流对象中。(简而言之,可以理解为写给浏览器)

在PrintUpperTag进行了如下操作:

if (items!=null) {for (Object obj: items) {getJspContext().setAttribute(var, obj);getJspBody().invoke(null);}}

然后在jsp页面中进行获取即可

这篇关于Jstl自定义标签及其生命周期、属性标签、及其读取文本练习、JspFragment输出标签体(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125253

相关文章

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

vue监听属性watch的用法及使用场景详解

《vue监听属性watch的用法及使用场景详解》watch是vue中常用的监听器,它主要用于侦听数据的变化,在数据发生变化的时候执行一些操作,:本文主要介绍vue监听属性watch的用法及使用场景... 目录1. 监听属性 watch2. 常规用法3. 监听对象和route变化4. 使用场景附Watch 的

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

C#实现SHP文件读取与地图显示的完整教程

《C#实现SHP文件读取与地图显示的完整教程》在地理信息系统(GIS)开发中,SHP文件是一种常见的矢量数据格式,本文将详细介绍如何使用C#读取SHP文件并实现地图显示功能,包括坐标转换、图形渲染、平... 目录概述功能特点核心代码解析1. 文件读取与初始化2. 坐标转换3. 图形绘制4. 地图交互功能缩放

java读取excel文件为base64实现方式

《java读取excel文件为base64实现方式》文章介绍使用ApachePOI和EasyExcel处理Excel文件并转换为Base64的方法,强调EasyExcel适合大文件且内存占用低,需注意... 目录使用 Apache POI 读取 Excel 并转换为 Base64使用 EasyExcel 处

Git打标签从本地创建到远端推送的详细流程

《Git打标签从本地创建到远端推送的详细流程》在软件开发中,Git标签(Tag)是为发布版本、标记里程碑量身定制的“快照锚点”,它能永久记录项目历史中的关键节点,然而,仅创建本地标签往往不够,如何将其... 目录一、标签的两种“形态”二、本地创建与查看1. 打附注标http://www.chinasem.cn

SpringBoot AspectJ切面配合自定义注解实现权限校验的示例详解

《SpringBootAspectJ切面配合自定义注解实现权限校验的示例详解》本文章介绍了如何通过创建自定义的权限校验注解,配合AspectJ切面拦截注解实现权限校验,本文结合实例代码给大家介绍的非... 目录1. 创建权限校验注解2. 创建ASPectJ切面拦截注解校验权限3. 用法示例A. 参考文章本文

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资