在JSP中使用自定義標籤

1. 介紹

在這篇文章中,咱們來學習在jsp中怎樣訪問一個自定義的標籤。就是自定義一個標籤:xyz。咱們將學習訪問在prefix: xyz與/prefix:xyz標籤內的內容。html

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

2. 實例:

在這個例子中,咱們實現將自定義的標籤中顯示內容。 處理類:Details.java 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");
   }
}

TDL文件: message.tld 將 message.tld 文件放入WEB-INF 文件夾裏:less

<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.jspjsp

<%@ 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 Messagecode

相關文章
相關標籤/搜索