给出一个Taglib的BODY_BUFFERED,bodyContent的例子

2021-07-15 18:00:56 浏览数 (1)

6)BODY_BUFFERED,bodyContent的例子:

有 时你标签对应的java代码会从数据库或其他网络渠道获取数据。这些数据在最终返回jsp显示之前,需要一个过滤修改的过程。比如去掉某些政治敏感的词语 或像本例一样加入一个词语“马克-to-win”。这时就需要你用BODY_BUFFERED技术。顾名思义就是要把你返回jsp显示的body先 buffer一下,放在BodyTagSupport的bodyContent里,你可以随意修改之,最后再返回jsp,但是前提条件是在 doStartTag中的返回值要写成EVAL_BODY_BUFFERED,这样系统就会开辟bodyContent这个Buffer,供你运作。

例 1.2.6:

<%@ page contentType="text/html; charset=GBK" %>

<%@ taglib uri="/WEB-INF/tagExampleLib.tld" prefix="greeter" %>

<html>

<body>

<greeter:Hello>

Now 时间 is: <%=new java.util.Date() %> <br>

</greeter:Hello>

结束

</body>

</html>

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>mark-to-win</shortname>

<tag>

<name>Hello</name>

<tagclass>com.marktowin.HelloWorldTag</tagclass>

</tag>

</taglib>

/*顺序是: 4)doStartTag

4.5) doAfterBody

5)doEndTag*/

package com.marktowin;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

import java.io.*;

public class HelloWorldTag extends BodyTagSupport {

int count = 2;

public int doStartTag() {

System.out.println("doStartTag");

return EVAL_BODY_BUFFERED;

}

public int doAfterBody() {

System.out.println("doAfterBody.");

while (count > 0) {

count--;

/* EVAL_BODY_AGAIN requires that the body of the tag is evaluated. */

return EVAL_BODY_AGAIN;

}

return SKIP_BODY;

}

public int doEndTag() {

System.out.println("doEndTagqqq");

/*the following try catch will be no use if you use return BodyTagSupport.EVAL_BODY_INCLUDE,

but if you use return BodyTagSupport.EVAL_BODY_BUFFERED;, you must use this try catch,

otherwise, there will be no output from IE, because the former won't use bodyContent. the

former use "Evaluate body into existing out stream" */

try{

if(bodyContent != null) {

System.out.println("body content qixy is not null");

/*public JspWriter getEnclosingWriter() Get the enclosing JspWriter.

writeOut(Writer out) Write the contents of this BodyContent into a Writer.

*/

更多请看:https://blog.csdn.net/qq_44594371/article/details/103183489

jsp

0 人点赞