How to access body of Custom tags in JSP tutorial

In the last tutorial we learnt how to create and use custom tags in JSP. In this tutorial we will see how to access the body of custom tag. For e.g. If our custom tag is xyz then we would learn to access the content between <prefix: xyz> and </prefix:xyz>

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

Example:

In this example custom tag will append a String to its own body and will display the result.

Tag handler class: 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 file: message.tld

Remember to have this file in WEB-INF folder.

<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 Page: 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>

Output:

Test String Appended Custom Tag Message
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值