CodesJava

Easy learning with example program codes

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 javawithease
 */
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.javawithease.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.

Related Topics:

JSTL (JSP Standard Tag Library) with example.
JSTL Core Tags with example.
JSTL Formatting Tags with example.
JSTL Functions with example.
Steps to create Custom tags with body in jsp with example.
Custom tag with attributes.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki