Thursday, 6 October 2016

How to pass Parameters in Custom tags in JSP?

In the previous blog post, we have learnt how to create custom tags in JSP. Today we'll look into passing parameters in custom tags in JSP.

Lets take an example for passing parameters in Custom tags in JSP. Suppose we want to find the cube of a given number using custom tags. So we will create custom tag like below -

<mytag:cube num="8" />

For passing parameter in Custom tag, we will follow the same steps which we followed for creating custom tags.

First of all we'll create Tag Handler Class -

Cube.java

package com.anjan;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class Cube extends TagSupport{

private int num = 0;

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

public int getNum(){
return this.num;
}

public int doStartTag() throws JspException {  
JspWriter out=pageContext.getOut();  
   try{  
       out.print(num*num*num);  
   }catch(Exception e){e.printStackTrace();}  
     
   return EVAL_PAGE
}    

}

We'll now create TLD File where we'll specify our tag name, tag handler class and tag attribute.

customDemo.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://tomcat.apache.org/example-taglib</uri>  

<tag>
<name>cube</name>
<tag-class>com.anjan.Cube</tag-class>

<attribute>  
    <name>num</name>  
    <required>true</required>  
</attribute>
</tag>

</taglib>


Now we are done with the creation of our custom tags. Now we have to use the tags in JSP page.

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%@ taglib uri="WEB-INF/cutomDemo.tld" prefix="mytag" %>
<title>Demo Page</title>
</head>
<body>
Cube of 8 <mytag:cube num="8" />
</body>
</html>


We'll get the below output when we test our project in browser -

Cube of 8 : 512

No comments:

Post a Comment