<taglib:tutorial lesson="8"/>

In this lesson, we will look at how we can use a custom Tag to access user information given to us in the Request..

1 Lesson 8, Accessing user information

    In this lesson, we will look at how we can use a custom Tag to access user information given to us in the Request.

    We will build a Tag that will retrieve the date the current file was last modified, and then format this date using a Locale. We will then update our Taglib descriptor and repackage our Taglib.

    Throughout this lesson, we will continue to use the setup previously defined for this tutorial. You should feel comfortable about the TagSupport class before starting on this lesson.

2 Creating the last modified Tag

    We will start with creating the Tag that we will use to retrieve the last modified date and format that with the given Locale.


    Figure 1: The LastModifiedTag class

    If no Locale is given, we will use the Request to get hold of the users Locale. If that is not accessible, we will rely on the systems default Locale.

    1. In the '/WEB-INF/classes/com/acme/tag/' directory, create a new class called 'LastModifiedTag.java' with the following content:


      package com.acme.tag;

      import javax.servlet.jsp.*;
      import javax.servlet.jsp.tagext.*;
      import javax.servlet.http.*;
      import java.util.*;
      import java.net.*;
      Listing 1: Import statements

      In the code above, we import javax.net.* to get the URL handling needed.

    2. Continue with the following:


      public class LastModifiedTag extends TagSupport
      {
      private Locale locale;
      private HttpServletRequest request;
      Listing 2: The class declaration

      We will use the locale variable to hold any Locale sent in as parameter to our Tag.

    3. Continue with the following:


      public LastModifiedTag()
      {
      super();
      }

      public void setLocale(Locale locale)
      {
      this.locale=locale;
      }
      Listing 3: The constructor

      The Container will use the method above to set the locale variable, which we will use later (if set) to format the last modified date.

    4. Continue with the following:


      public int doEndTag() throws javax.servlet.jsp.JspException
      {
      try
      {
      request= (HttpServletRequest) pageContext.getRequest();
      Listing 4: Overriding the doEndTag() method.

      This method will be called by the Container at the end of the Tag. We start with retrieving the users Request from the PageContext.

    5. Continue the method with the following:


      if(locale==null)
      {
      locale=request.getLocale();
      }
      if(locale==null)
      {
      locale=Locale.getDefault();
      }
      Listing 5: Overriding the doEndTag() method (continued)

      In the code above, we first check if the Tag was given a locale parameter. If not, we get the Locale specified in the users Request. If we could not get any Locale from the users Request, we use the system default Locale instead.

    6. Continue the method with the following:


      URL url=pageContext.getServletContext().getResource(request.getServletPath());
      Listing 6: Overriding the doEndTag() method (continued)

      Above, we use the ServletContext to find the resource mapped to the pathname returned from the method getServletPath(). The resource is returned as a URL. It is up to the servlet container to implement the URL handler and URLConnection objects needed to access the resource, so we don't really have to care about that..

    7. Continue the method with the following:


      long miliseconds;
      if(url.getProtocol().equals("file"))
      {
      miliseconds=new java.io.File(url.getFile()).lastModified() ;
      Listing 7: Overriding the doEndTag() method (continued)

      Above, we check to see what protocol is needed to access the URL. We do this because of a bug in Suns VM regarding FileURLConnection, which for some reason causes 0 to be returned if we try to open a connection and get the last modified date. So instead we use File to open the file with the name given to us by the url.getFile(), and then use the File's getLastmodified() method.

    8. Continue the method with the following:


      }
      else
      {
      miliseconds = url.openConnection().getLastModified();
      }
      Listing 8: Overriding the doEndTag() method (continued)

      Above, we use the URL's openConnection() to retrieve a URLConnection object that represents a connection to the object that the URL refers to. Whatever URLConnection object we get in return, we use to get the last modified date.

    9. Continue the method with the following:


      if(miliseconds>0)
      {
      Date lastModified=new Date(miliseconds);
      pageContext.getOut().write(java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT, java.text.DateFormat.SHORT,locale).format(lastModified));
      }
      Listing 9: Overriding the doEndTag() method (continued)

      Above, we first check to make sure that we really got a last modified date value. We then use this value to create a new date. Finally, we use the Locale to format the date and then write it to the current JspWriter.

    10. Continue the method with the following:


      }
      catch(java.net.MalformedURLException mue)
      {
      throw new JspException(mue.getMessage());
      }
      catch(java.io.IOException ioe)
      {
      throw new JspException(ioe.getMessage());
      }
      catch(java.lang.NullPointerException npe){}
      Listing 10: Overriding the doEndTag() method (continued)

      Above, we catch the IO Exceptions that might be thrown when we try to write to the JspWriter or openConnections to the resource. Furthermore, we must catch any java.net.MalformedURLException thrown when we use the getResource() method of ServletContext. We have the NullPointerException catcher there if getResource would return null and we later try to use it.

    11. End the Tag with the following rows:


      return EVAL_PAGE;
      }
      }
      Listing 11: End of the Tag.

      Above, we tell the Container that the rest of the page should be evaluated.

      By now, your LastModifiedTag.java should look like this. Store the sourcecode in the /WEB-INF/classes/com/acme/tag/ directory as LastModifiedTag.java

    12. Compile the Tag.

3 Update the Tag Library Descriptor

    We now need to tell our JSP Container about our new Tag.

    1. Open your 'taglib.tld' from your '/WEB-INF/' directory with your favourite editor.

    2. Add the following description for your new Tag:


      <tag>
      <name>lastModified</name>
      <tagclass>com.acme.tag.LastModifiedTag</tagclass>
      <bodycontent>empty</bodycontent>
      <info>
      Displays when a page was last modified.
      If no Locale is given, the users Locale is used for formating.
      If no user Locale is found, the system default Locale is used.
      </info>
      <attribute>
      <name>locale</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      </attribute>
      </tag>
      Listing 12: Tag entry in descriptor.

    Your taglib.tld should now look like this. Store the descriptor in the /WEB-INF/ directory as taglib.tld.

4 Presenting your Tag

    In order to test your Tag, you will need a JSP page that uses it.

    1. Create a file called lastModified.jsp and add the following lines:


      <%@ taglib uri="mytags" prefix="mt" %>
      <HTML>
      <HEAD>
      <TITLE>Last Modified</TITLE>
      </HEAD>
      <BODY>
      <HR>
      <P>This page was last updated <mt:lastModified/> .</P>
      <HR>
      </BODY>
      </HTML>
      Listing 13: A sample JSP page.

    The page above will display a message stating when it was last updated.

    If you've typed in this correctly, your lastModified.jsp should look like this.

5 Using your new Tag

    We are now ready to use our new Tag.

    Open the URL http://localhost/taglib/lastModified.jsp in a normal web browser. Hopefully the result looks like this.

    Continue with lesson 9, "Accessing the EJB layer".

Copyright © 2005 IronFlare AB