Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình

Tạo custom tag JSP chấp nhận attribute từ trang JSP cha

Để custom tag chấp nhận giá trị attribute, lớp tag cần triển khai phương thức setter tương tự JavaBean setter.

Lớp Tag Handler

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

public class HelloTag extends SimpleTagSupport {
  private String message;
  public void setMessage(String msg) {
    this.message = msg;
  }
  StringWriter sw = new StringWriter();
  public void doTag() throws JspException, IOException {
    if (message != null) {
      JspWriter out = getJspContext().getOut();
      out.println(message);
    } else {
      getJspBody().invoke(sw);
      getJspContext().getOut().println(sw.toString());
    }
  }
}

Tên attribute là "message", nên setter là setMessage().

Cấu hình TLD

<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example TLD with Body</short-name>
  <tag>
    <name>Hello</name>
    <tag-class>com.tutorialspoint.HelloTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
      <name>message</name>
    </attribute>
  </tag>
</taglib>

Sử dụng trong JSP

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>
<html>
  <head> <title>A sample custom tag</title> </head>
  <body>
    <ex:Hello message = "This is custom tag" />
  </body>
</html>

Kết quả

This is custom tag