Thursday, January 12, 2012

Custom Tags

Our code for showing the date picker (calendar) was terse, but... cryptic.
Javascript in JSP always makes things hard to read and difficult to maintain.

One solution to this is to create Custom Tags.

A Custom Tag allows you to put javascript (or anything else - let us not worry about that for now) inside a Java classe, to create 'tag libraries'.

By referring to these tags, it is possible to simplify the JSP.

For example, we could create a custom tag to encapsulate the javascript we put in for the datepicker, and our JSP would then reduce to this:

 <html>   
<head>
<link type="text/css" rel="Stylesheet" href="../css/jquery-ui-1.8.17.custom.css"/>
<script src="../js/jquery-1.7.1.min.js"></script>
<script src="../js/jquery-ui-1.8.16.custom.min.js"></script>
<script src="../js/jquery.ui.core.js"></script>
<script src="../js/jquery.ui.datepicker.js"></script>
<%@ taglib uri="/WEB-INF/tlds/ConfuciusTags.tld" prefix="confucius" %>
</head>
<body>
<confucius:datetag id="birthdate" label="Enter your birthday"/>
</body>
</html>


Compare this <body> with the JSP in the previous blog.
This one is Cleaner, Readable and Reusable.

No comments: