Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

April 20, 2010

Custom Tags, TLD, Tag Files, El Functions, what is the difference?

If you are starting out with Java Custom Tag Development, you have probably come across the terms in the title of this article.

But if you are like me, it probably took you a while to wrap your head around all the terms, how the relate to each other, and most importantly what is the difference between them.

  • What is a custom tag?
  • What is a TLD file?
  • What is the difference between a TLD file and a Tag File?
  • What is an EL Function?

In this article I will try to explain some of these questions and terms.

There is another article on this blog which you may find useful.

Custom Tags

A Custom Tag is a generic term for code which simplifies the writing of Java code (eg. scriptlets, classes, etc).

A simple example of a custom tag is: <myTagLibrary:doSomething/>

Custom Tags - JSTL (Java Standard Tag Library)

JSTL is a collection of standard tags which give you common functionality, that you otherwise would have to write yourself as scriptlets or expressions inside your JSP pages

For example:

Instead of putting this scriptlet in your JSP page


<table>

<%
  String[] items = (String[]) request.getAttribute("movieList"); 
  String movie = null;
  for(int i = 0;i<items.length;i++){
    movie = items[i];  
%>

<%
  <tr>
     <td><%= movie %></td>
  </tr>    
%>

</table>

You can make it much simpler by using a JSTL tag


<table>
  <c:forEeach var="movie" items="${requestScope.movieList}">
  <tr>
    <td>${movie}</td>
  </tr>  
  </c:forEach>
</table>

Custom Tags - Writing your own

You can also write your own Custom Tags. See how

Custom El Functions

A custom El Function is a customized method that you can invoke using the JSP Expression Language.

A simple custom EL Function looks like this: ${myTagLibrary:randomColor()}

How do I create a custom el function?

TLD Files

A TLD file (*.tld), or Tag Library Descriptor file, is an XML file containing data which defines a Custom Tag OR an El Function

How do I create a TLD file?

Tag Files

A Tag File (*.tag), is a way for non-Java developers to build custom tags without writing a Java class (eg. a Custom Tag Handler class).

A *.tag file can be any valid *.jsp file. So you can just rename a jsp file to *.tag, but there are certain rules about where in your application's directory structure you have to place a *.tag file.

A Tag File is usually used when you need simpler functionality in your custom tags, for complex things a Custom Tag Handler class is better.

How do I create a simple Tag File?

To learn more about Tag Files also try these articles:

Easy Custom Tags with Tag Files, Part 1 and Oracle article on Tag Files

Questions

What is the difference between a TLD File and a Tag File?

A TLD File is an XML file which declares the functionality of custom tags or EL Functions, while a Tag File (which is actually a renamed *.JSP file), allows you to declare Custom Tags without writing a Custom Tag Handler (eg. a Java class).

Creating a simple JSP Tag File

This is a simple tutorial for creating a very basic Tag File for use in Java Web Applications:

A Tag File (*.tag), is a way for non-Java developers to build custom tags without writing a Java class (eg. a Custom Tag Handler class).

Step 1

Create the file coolimage.jsp with the following content:

  <%@ attribute name="imageName" required="true" rtexprvalue="true"/>
 
   Here is a cool image: <img src="images/doggy.png" imageName="${imageName}">

Step 2

Rename the file coolimage.jsp to coolimage.tag and put it under: WEB-INF/tags/coolimage.tag

Step 3

Create the test.jsp page which will use the Tag File:


<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>

<myTags:coolImage imageName="My Favorite Doggy"/>

Step 4

Don't forget to add doggy.png to your webapp/images folder.

If everything worked well, you have now just created a simple JSP Tag File.

Things to keep in mind when creating Tag Files

To make sure the Servlet Container finds your Tag File place your *.tag file in file(s) any of these locations:

  • WEB-INF/tags/
  • WEB-INF/lib/mylibrary.jar -> META-INF/tags/ //inside the META-INF folder of your jar file

Using a Tag File inside a jar file

If you have a Tag File inside a jar library, it must have a an appropriate entry in a TLD file.

The TLD file you will need in this case is similar, but not the same as the TLD file which declares a Custom Tag (See my other tutorial on Custom Tags). It only specifies the location of the Tag File (not it's functionality) so the container can find it.

The TLD file you will need in this case will look something like this:

April 15, 2010

Custom Tags and Custom EL Functions in JSP Pages

What is a Custom Tag?

A Custom Tag is a generic term for simplifying or eliminating Java code inside JSP pages (eg. eliminating scriptlets). A typical custom tag looks like this:

<myTagLibrary:doSomething/>

What is a Custom EL Function?

A Custom EL Function is a method that you can invoke using the JSP Expression Language. A typical Custom EL Function looks like this:

${myTagLibrary:randomColor()}

In order to create a Custom Tag or a Custom EL Function you will need two things:

  1. A Java class to define what the Custom Tag or Custom El Function will do
  2. A TLD file in which will specify the Java class and method to use, and how your Custom Tag or El Function will be called.

Creating the TLD file

Here is a TLD file which will defines an EL Function and a Custom Tag. We're going to call this file funkytaglibrary.tld.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" 
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
  
 <tlib-version>1.0</tlib-version>
    <short-name>MyLibrary</short-name> <!-- Used for tools to display -->
    <uri>FunkyTagLibrary</uri>         

    <!-- Define a Custom EL Function -->
    <function>
        <name>randomColor</name> <!-- Will be used to call your El Function:   ${myTagLibrary:randomColor()} inside your JSP page -->
        <function-class>foo.RandomColorGenerator</function-class>
        <function-signature>String pickRandomColor()</function-signature>
    </function>
 
    <!-- Define a Custom Tag -->
    <tag>
        <description>This tag prints a random number.</description>
        <name>randomNumber</name>   <!-- Will be used to call your tag  <myTagLibrary:randomNumber greaterThan="2"/> -->
        <tag-class>foo.RandomNumberGenerator</tag-class>
        <body-content>empty,scriptless,tagdependent or JSP</body-content>
        
        <!-- If your Custom Tag has attributes you will define them here --> 
        <attribute>
            <name>greaterThan</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>     <!-- if true, you can have things like ${myNumber} as the attribute value -->
        </attribute>
           
    </tag>
</taglib>

Your JSP file will have to contain the following directive to make use of this TLD file
<%@ taglib prefix="myTagLibrary" uri="FunkyTagLibrary" %>

Creating the Java class

In order to implement the functionality of the Custom Tag or Custom EL Function defined in the TLD field above, you also have to have a Java class for each.

Class for implementing the custom EL Function randomColor()


package foo;  

public class RandomColorGenerator{
 public static String pickRandomColor(){   //notice that this method doesn't have to be  the same as the one that will apear in your tag 'randomColor'. This is only true for a class that implements a Custom El Function.
  String [] colors = new String[3];
  colors[0] = 'Red';
  colors[1] = 'Blue';
  colors[2] = 'Yellow';
        return color[Math.abs(r.nextInt()) % 4]; //return one of the colors in array at random
    }
}

In order to implement the functionality of the Custom Tag or Custom EL Function defined in the TLD field above, you also have to have a Java class for each.

Class for implementing the custom tag functionality

Some people refer to a class that implements a custom tag functionality as a Tag Handler


package foo;
public javax.servlet.jsp.JspException;  
public javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class RandomNumberGenerator extends SimpleTagSupport{
 private String greaterThan; //stores the value of the greaterThan attribute of the custom tag

 @Override
 public void doTag() throws JspException, IOException{ //this is the method that is called when the custom tag  is called from a JSP page 
  int randomNumber = (int)Math.random() * (greaterThan+1); //generate a random number, which is greater than the 'greaterThan' attribute's value 
  getJspContext().getOut().write(randomNumber); 
 }

 public void setGreaterThan(int number){ //the method name must match the attribute name defined in the TLD file
  greaterThan = number;
  } 
 }
}

Where do I put the TLD file?

In order for the Servlet Container to find the TLD file and use it, you can put the funkytaglibrary.tld in any of the following locations:

  • WEB-INF/funkytaglibrary.tld
  • WEB-INF/subfolder/funkytaglibrary.tld
  • WEB-INF/lib/mylibrary.jar -> META-INF/funkytaglibrary.tld //inside the META-INF folder of your jar file
  • WEB-INF/lib/mylibrary.jar -> META-INF/subfolder/funkytaglibrary.tld //inside a META-INF sub folder of your jar file

Calling the Custom Tag and Custom EL Function from JSP

test.jsp

<html>
 <body>
  <%-- call your custom el function --%>
  Here is a random color: ${myTagLibrary:randomColor()}.

  <%-- call your custom tag --%>
  Here is a random number: <myTagLibrary:randomNumber greaterThan="10"/> 
 </body>
</html>

April 8, 2010

The evolution of Servlets and JSP

This article is about clarifying how to use Servlets and JSP pages. When starting out to learn Java Web Application development you will undoubtedly have many questions about how all the terms and terminology interacts with each-other, or what the benefit is. Eg. Scriptlets, Servlets, Tags, Expression Language, Standard Actions, Custom Tags, Directives, etc

If you didn't have the good fortune to stumble upon a good book to give you a clear and solid foundation you will often be confused about when to use what etc.

So here is a simple introduction to why the basic Java Web Application Development technologies were built.

In the beginning

In the beginning there was darkness (and simplicity). The only things that existed were static html pages. They would have html and text, and that's it.

Soon after came dynamic pages, which could show things like the current date or timestamp. The server would generate the html code, and everyone was happy (see Perl and CGI scripts)

Servlets

After Java emerged, Servlets were created to allow dynamic pages to be written using the Java language.


public class NiceServlet extends HttpServlet
{ 
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
   PrintWriter out = response.getWriter(); 
   out.println("<html><head><title>A Nice Servlet</title></head><body>"); 
   out.println("The nice body of this servlet displays the date for you: "+(new java.util.Date())); 
   out.println("</body></html>"); 
   out.close(); 
 } 
}

]]>

For a time things were good, as Servlets could leverage the power of Java to create just about any kind of html content.

  • Advantages:Now you can generate dynamic html with Java.
  • Disadvantages: Very hard to maintain and cumbersome to write and update once the dynamic page starts to have a lot of stuff.

But things became complicated, because creating large dynamic html page content with lots of data required many lines of out.println() statements. So something else came along...

Scriptlets and Expressions


<% scriptlets %>

<%= expressions %>

Scriptlets and Expressions were created to simplify the generation of code from a page. With the creation of JSP pages, you could now write a scriptlet or expression and the Servlet Container (eg. Tomcat) would dynamically generate all the servlet code for you automatically (eg. all the out.println() statements).

There were other things as well that simplified things. Directives, declarations and of course server side comments.


<%@ directives %> //include other files or import java packages

<%! declarations %> //declare variables or methods outside of the service() method

<%-- comments --%> 

  • Advantages:You can do anything with Scriptlets and Expressions that you can write with Java code.
  • Disadvantages: A lot of custom code which makes the JSP page hard to maintain and read.

Standard Actions

To simplify things even more, now you didn't even have to use Scriptlets or Expressions, you could use Standard Actions

Why, because JSP pages started to get large and bogged down with Scriptlets, Expressions all over the place. It was hard to maintain (less by a Java developer) but mostly by web designers. Or at least that was the drive to simplify things (I still think today if you're developing Java web applications you need to be familiar with both HTML and Java equally);

The getProperty Standard Action in Action. The following code will display the name property of the bean called 'user' (if it's defined);
<jsp:getProperty name="user" property="name" />
The above standard action will allow the Servlet Container to convert the code to the following (which you otherwise would have had to write)
User user = (User)request.getAttribute("user");
out.println(user.getName());

But Standard Actions had a shortcoming. They weren't compatible with indexed properties. So having a Garden object which had a Tree object which had a getName() property would be a problem as you couldn't do this:

<jsp:getProperty name="garden" property="tree.name" />

Standard Actions would also do silly things like throw a Null pointer exception if the property didn't exist or was 'null'

  • Advantages: Much more cleaner and quicker to use than scriptlets and expressions
  • Disadvantages: Don't work with anything except String or primitive bean properties

EL (JSP Expression Language)

So came EL (JSP Expression Language) which allows you to do all of the above (introduced with JSP 2.0 Specification)

I'm not going to go into detail here about how the EL is used and what it does, but rest assured it's cool, once you digg it that is. I'll leave it up to others to get into it, but here's a useful link if you don't know anything about EL A JSTL Primer Part 1 - The Expression Language.

  • Advantages: Much easier to use. Empty or null values don't throw errors.
  • Disadvantages: No easy way to loop through collections or arrays.

Unfortunately though even EL has its shortcoming. It can't for one thing loop through collections or arrays.

JSTL (Java Standard Tag Library)

JSTL are custom tags which let you do things like formatting data or iterating through collections and displaying each element in a table row for example.

JSTL Tags can be used as easily as JSP standard actions. That's one advantage.

The main advantage however is that JSTL combined with EL will cover 99% of the things you will need in a JSP file.

Custom Tag Libraries

Finally, for those .1% of cases where you need some complex behavior specific to your application, you can also create your own custom tags. But that is quite an advanced topic, if any of the previous things I mentioned in this post aren't too familiar to you

If you are looking just for some custom tags, here is a good website with various libraries. JSP Tag Libraries.

So that's a quick run through the basic evolution of Servlets and JSPs. I hope you found this article useful. Please let me know if you did.

January 21, 2010

Internationalization for client side scripting in JSP applications

If you are using JSP in a web application which uses i18n, you probably came across the problem of having to internationalize your client-side validation error messages as well, such as JavaScript error messages.

The problem is that i18n settings are usually defined at the application level, such as the web deployment descriptor of your Tomcat server or in your Java classes, and there's no straight forward way of applying the same settings to your client side code.

Here is a solution (maybe not the best one) but nonetheless, which will let you do client-side internationalized messages with relative ease for any JSP/Servlet based application:

Step 1: Create the files

Create 2 or more js files for each language you are using and place them in your app directory structure

  • webapproot/scripts/validation.strings.js //english version
  • webapproot/scripts/validation.strings.ro.js //romanian version

Step 2: Add the localized strings to each file

validation.strings.js: validation.strings.ro.js:

Step 3: Include the localized scripts based on your locale

Add the following code to the jsp page on which you will be using internationalized client-side messages. In our case we only have two languages, and the default is english (validation.strings.js), but you can modify the code below to use any number of them.


<c:choose>
   <c:when test="${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session'] eq 'ro'}">
      <script src="<%= request.getContextPath()%>/scripts/validation.strings.ro.js" type="text/javascript"></script>
   </c:when>
   <c:otherwise>
      <script src="<%= request.getContextPath()%>/scripts/validation.strings.js" type="text/javascript"></script>        
   </c:otherwise>    
</c:choose>

To find out more about setting the locale in a Java Web Application using Tomcat read this post

Step 4: Call the JavaScript code

Finally you can now reference an internationalized JavaScript message from your JSP page as in the example below:

Step 5: Done

If you did everything correctly and your locale is set to 'ro', you should get an alert saying 'Acest camp nu a fost completat'