Custom tag with attributes

Custom tags:

Custom tags are the user defined tags. These tags are mainly used for code re-usability. We can define a custom tag with any number of attributes. Let us discuss it with the below example.

Example:

CustomTagWithAttribute.java

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * This class is used for defining a custom tag with attributes.
 * @author W3schools360
 */
public class CustomTagWithAttribute extends SimpleTagSupport{
	//tag attribute
	private int num;
	
	public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      try{
    	  out.println("Square of " + num + " = " + num * num);
      }catch(Exception e){
    	  e.printStackTrace();
      }      
    }

	public void setNum(int num) {
		this.num = num;
	}	
}

squaretag.tld


	 1.0
	 2.0
	 Our first custom tag
	 	 
	 
		 squareTag
		 
                   com.w3schools360.customtags.CustomTagWithAttribute
                 
		 empty
		   
	    	num  
	    	true  
	      
	 

test.jsp

<%@ taglib prefix="stag" uri="WEB-INF/squaretag.tld"%>


	
		custom tag with attribute example
	
	
		
	

web.xml


	
  
          test.jsp
  	


Output:

jsp example 68
 
Download this example.
 
Next Topic: Struts Tutorial with examples.
Previous Topic: Steps to create Custom tags with body in jsp with example.