Skip to content

Latest commit

 

History

History
73 lines (58 loc) · 1.93 KB

37.md

File metadata and controls

73 lines (58 loc) · 1.93 KB

如何访问自定义标签的主体

原文: https://beginnersbook.com/2014/01/how-to-access-body-of-custom-tags-in-jsp-tutorial/

在上一个教程中,我们学习了如何在 JSP 中创建和使用自定义标签。在本教程中,我们将了解如何访问自定义标签的主体。对于例如如果我们的自定义标签是xyz,那么我们将学习访问<prefix: xyz></prefix:xyz>之间的内容

<prefix: xyz>
Body of custom tag: This is what we will access in the below example
</prefix:xyz>

示例:

在此示例或自定义标签中,将String附加到其自己的主体并显示结果。

标签处理程序类Details.java

package beginnersbook.com;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class Details extends SimpleTagSupport {
   //StringWriter object
   StringWriter sw = new StringWriter();

   public void doTag() throws JspException, IOException
   {
       getJspBody().invoke(sw);
       JspWriter out = getJspContext().getOut();
       out.println(sw.toString()+"Appended Custom Tag Message");
   }
}

TLD 文件message.tld,请记住将此文件放在WEB-INF文件夹中。

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag: MyMsg</short-name>
<tag>
<name>MyMsg</name>
<tag-class>beginnersbook.com.Details</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>

JSP 页面index.jsp

<%@ taglib prefix="myprefix" uri="WEB-INF/message.tld"%>
<html>
<head>
  <title>Accessing Custom Tag Body Example</title>
</head>
<body>
  <myprefix:MyMsg>
    Test String
  </myprefix:MyMsg>
</body>
</html>

输出:

Test String Appended Custom Tag Message