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 w3spoint
 */
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

<taglib>
	 <tlib-version>1.0</tlib-version>
	 <jsp-version>2.0</jsp-version>
	 <short-name>Our first custom tag</short-name>
 
	 <tag>
		 <name>squareTag</name>
		 <tag-class>
                   com.w3spoint.customtags.CustomTagWithAttribute
                 </tag-class>
		 <body-content>empty</body-content>
		 <attribute>  
	    	<name>num</name>  
	    	<required>true</required>  
	    </attribute>  
	 </tag>
</taglib>

test.jsp

<%@ taglib prefix="stag" uri="WEB-INF/squaretag.tld"%>
 
<html>
	<head>
		<title>custom tag with attribute example</title>
	</head>
	<body>
		<stag:squareTag num="25"/>
	</body>
</html>

web.xml

<web-app>
 
  <welcome-file-list>
          <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>	
 
</web-app>

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.

 

Please Share