Using Custom Tag in JSP
How to use Custom Tag?
Explanation
To use custom tags we have to create "Java" files which are defined in a "tld" file. Here we have created a Java file Hello.java in which we are specifying a tag functionality.
Example:Hello.java
package mytag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* Simple tag example to show how content is added to the
* output stream when a tag is encountered in a JSP page.
*/
public class Hello extends TagSupport { private String name=null;
/**
* Getter/Setter for the attribute name
as defined in the tld file
* for this tag*/
public void setName(String value){
name = value;
}
public String getName(){
return(name);
}
/**
* doStartTag is called by the JSP container
when the tag is encountered */
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Welcome <b>" + name +
"</b> </td></tr>");
else
out.println("<tr><td> Hello World </td></tr></table>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not
supporting a body for this
// tag.
return SKIP_BODY;
}
/**
* doEndTag is called by the
JSP container when the tag is closed */ public int doEndTag(){
return EVAL_PAGE; }
}
In the above Custom Tag example we have used the methods "set", "get" to set the initial values, return values. To define a class in a tag library the two methods "doStartTag()" and "doEndTag()" are used. In the doStartTag()what are the actions to be performed in the start is specified. In the doEndTag() the actions to be done in the end are specified.
Following is the code of a java file to encrypt a string using the "md5" algorithm. Example: Encrypt.java
package mytag;
/**
* @author Rajesh
*/
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Encrypt extends TagSupport{
private String name;
public void setName(String value){
String result=value;
try{
java.security.MessageDigest d = null;
d = java.security.MessageDigest.getInstance("MD5");
d.reset();
d.update(value.getBytes());
byte by[]=d.digest();
for (int i=0; i < by.length;i++) {
result +=
Integer.toString( ( by[i] & 0xff ), 16);
}
name=result;
}
catch(Exception e){
name=e.toString();
}
}
public String getName(){
return name;
}
@Override
public int doStartTag() { try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Your Encrypted Password is="
+ name + " </td></tr>");
else
out.println("<tr><td>Hm now we can't</td></tr>");
} catch (Exception ex) {
throw new Error("Opps error "+ex);
}
return SKIP_BODY;
}
@Override
public int doEndTag(){
return EVAL_PAGE;
}
}