How can I create custom tag in JSP which can accept attribute from parent jsp page?

JSPJava 8Object Oriented ProgrammingProgramming

You can use various attributes along with your custom tags. To accept an attribute value, a custom tag class needs to implement the setter methods, identical to the JavaBean setter methods as shown below −

package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;

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) {
         /* Use message from attribute */
         JspWriter out = getJspContext().getOut();
         out.println( message );
      } else {
         /* use message from the body */

The attribute's name is "message", so the setter method is setMessage(). Let us now add this attribute in the TLD file using the <attribute> element as follows −

   <short-name>Example TLD with Body</short-name>




Let us follow JSP with message attribute as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

      <title>A sample custom tag</title>

      <ex:Hello message = "This is custom tag" />

This will produce the following result −

This is custom tag
Updated on 30-Jul-2019 22:30:25