Monday, 21 May 2012

How to create custom tags for JSPs in Eclipse

We have seen so many frameworks that come with their own set of custom tags. Why not create a custom tag of our own that we can use in our JSPs? So, today we will be creating a simple custom tag to use in our JSP (2.0). Yes, I emphasize on JSP 2.0 because the process is a lot simpler and much more concise than what it was in JSP 1.x.

Let us get started now. I am using Eclipse Indigo for this project.

Step 1: Create a new Dynamic Web Project
We select File -> New -> Dynamic Web Project. Enter the project name, and choose Apache Tomcat 6.0 as the target runtime.
Step 2: Create a new file folder in the /WEB-INF directory.
We need to create a new folder /WEB-INF/tags. We can do this by right clicking on the WEB-INF folder, and selecting New -> Folder. This is the folder that will contain all the custom tags.

Step 3: Create a new tag file
Right click on the /WEB-INF/tags folder, and select New -> Other. There, we scroll down to Web, and choose JSP Tag.
Next, we give it a name. I call it sayHello.
Once the name of the tag is chosen, I choose the Tag template.
That creates the tag file. Now, we enter the necessary code to make the tag functional. A tag file is almost identical to a JSP file. So, my tag is going to take one attribute, named to. That attribute is going to be mandatory.
<%@ tag language="java" pageEncoding="UTF-8"%>
<%@ attribute name="to" required="true"%>

<%
	out.println("Hello <b>"+
				getJspContext().getAttribute("to")+
				"</b>");			
%>
However, you can also make use of expression language (EL), to make the tag file much more concise as follows,
<%@ tag language="java" pageEncoding="UTF-8"%>
<%@ attribute name="to" required="true"%>

Hello <b>${to}</b>
Step 4: Create a new JSP file
We now create a JSP file to use our custom tag. Here I make use of the taglib directive that tells the JSP that it uses my custom tags, found in the directory /WEB-INF/tags and the prefix I use to indicate that it is a custom tag would be j. Here is the code for it,
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="j" %>    
<!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=UTF-8">
<title>JDepths Tag Test</title>
</head>
<body>
	<j:sayHello to="Hathy"/>
</body>
</html>
That is all you need to do. Now when you run your project, the page should render the message,
Hello Hathy

There, you can now go ahead and create all sorts of tags to make your JSPs contain simpler code. If you have any reviews, comments or suggestions please do write to me. Thanks for reading.

No comments:

Post a Comment