Wednesday, April 6, 2011

Chapter 32: Opening and Closing JSP Tags

The previous chapter was rather boring with the story or history of the JSP Technology. Starting this chapter, we are getting right down to business. In this chapter we are going to learn how to use the following JSP Tags

2. Directive
3. Declaration
4. Scriptlets
5. Expressions

So, lets get started!!!


There are two types of comments that you can use in a JSP Page. They are:
This is a JSP comment.
< % -- comment -- % >

The compiler ignores everything embedded in it, including elements, directives, and actions.
This is an HTML comment.
< ! -- comment -- >

The compiler treats the HTML comment as text, so it passes it through to the output stream unaltered. The text that results from any JSP, including HTML comments, is then passed on to the browser, which doesn't display it. However, JSP comments are ignored during translation. For example

< ! -- page visited on: <%=(new java.util.Date()).toLocaleString()%> -- >
displays in the page source as
< ! -- page visited on April 05, 2011 -- >

Exam Trivia:

A JSP comment is ignored by the JSP engine: It is skipped by the compiler, as are comments in all Java source files. On the other hand, an HTML comment is added to the output stream because it is treated as pure text, which the servlet container simply passes through to the output stream. If there is a scriptlet embedded in an HTML comment, it will be processed normally. The JSP engine recognizes Java in an HTML comment, but the HTML viewer will not display it.


Directives are a communication link between the JSP page and the JSP container. Directives have this syntax:
<%@ directive { attribute="value" }* %>

Directives are not used to display text; they don't contribute anything into the current output stream. There are three directives: include, page, and taglib. Each directive has several attributes that affect how the container processes the page. Lets look at them one by one.

The include Directive

The syntax of the include directive is as follows:

<%@ include file="relativeURL" %>

The include directive is a placeholder that lets you include the text in another file. The text that is included by this directive is part of the translation into a servlet. It is good practice to decompose complex pages into several files. Doing so doesn't impact performance, but does make your code more manageable and even better – more readable. Header (for example, company logo image) and footer (for example, copyrights) information is a good candidate for using the include directive. If you want to include the results from another servlet or JSP then use the XML equivalent, because that way the JSP simply invokes the resource and takes the results. The include action instead of directive is sometimes the better choice, because that would include an outside file without recompilation.

Exam Trivia:
To simply add text from another file, but not parse it, use the XML equivalent . This tag includes a file at request time instead of translation time. Therefore content is not parsed, but rather included in place. The jsp:directive.include tag is the XML equivalent to the <%@include%> directive which is performed at translation-time.

The taglib Directive

The syntax of the taglib directive is as follows:

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

JSP technology makes it easy to embed Java code and functionality into HTML documents. However, the author has to know Java in order to use scriptlets. This is true for JavaBeans as well. You can use custom tags through the tag library facility. You can embed functionality into JSP pages with custom tags that look like XML or HTML. With custom tags, you are better able to separate presentation from business logic.

For now don't worry about JavaBeans and using them with JSPs. This is because, we will be covering it as a separate set of chapters. For now just know that A taglib is a mechanism that enables you to specify your own custom tags. JSP custom tags are merely Java classes with a special interface that makes it easy to access them from a JSP page.

You start by writing a class that implements the Tag interface like so:

public class MyFirstCustomTag implements Tag { }

You code the methods of the Tag interface, including setPageContext, doStartTag and doEndTag. The JSP container knows how to map the tag in the JSP to your custom MyFirstCustomTag class, where you encapsulate your functionality. Then you create a Tag Library Descriptor (TLD) file also called the .tld file, that tells the JSP container everything about your tag library. Finally, you use your tags in the JSP page by first including the taglib directive, then using the actual tags like so:

<%@ taglib uri="/WEB-INF/jsp/MyFirstCustomTaglib.tld" prefix="MyFirstCustomTag" %>
< body >

MyFirstCustomTag produces:

The page Directive

The page directive gives directions to the servlet engine about the general setup of the page. This directive will be covered in great detail as a separate chapter so for now just know that the page directive can be used to give instructions to the Servlet engine about the general setup of the page.


In Java you must always declare a variable before you use it. Mostly, you type Java the same in a JSP page, except for the delimiters. The syntax is almost identical except for the de-limiters and the expression (<%=somethingHere%>). A declaration declares one or more variables or methods. Once declared, you can use them later in the JSP page. Also, the scope of these declarations can be either local (for example, inside a block) or instance declaration (apply to the entire JSP page).

The syntax inside the delimiters is the same as Java, so you can declare any number of variables or methods within one declaration and you end each statement with a semicolon (Just like Java).

The following are some examples:

<%! int i = 0; %>

<%! int var1, var2, var3; %>

<%! MyTestClass obj = new MyTestClass(); %>

Exam Trivia:

You can use variables or methods that are declared in an imported package (using the page directive) or included page (using include) without declaring them directly in the current JSP page. So, you need to be careful not to have duplicate variable declarations.


The scriptlet is a way to include Java code directly in a JSP page. Aside from the requirement of having delimiters, it is just regular Java. The following is a simple example (please assume java.util.* has already been imported):

<% if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM) {%>
Time to go to office!
<% } else { %>
Time to go back home!
<% } %>

Scriptlets have access to the entire Java API. They are very powerful. Just remember that, all the test questions about Scriptlets will require you to recollect your Java Syntax. So as long as you remember your Java basics, you can crack al these questions. However, if you wish to refresh your Core Java skills, you can go to the SCJP Certification series and cover concepts like variable declarations, OO concepts, etc…


The basic syntax of the expression element is as follows:

<%= your_expression %>

An expression element contains Java code that is evaluated, converted to a string, and inserted into the output stream. Expressions are never terminated with a semicolon, a break with normal Java convention. Notice that an expression must be converted to a String. Internally, JSP replaces the expression element with a String to append to the output stream. During translation, the expression text is placed in a out.print(); statement when the container transforms the JSP page into a servlet. Therefore, you can treat it as text, such as place it in the middle of an HTML tag, or anywhere for that matter. For example, the following is how you could dynamically set the color of a font with an expression:

< font color="<%= Color.getCurrentColor() %>" >Colored Text< / font >

As another example, you could display the current date like so:
<%= (new java.util.Date()).toLocaleString() %>

Previous Chapter: Chapter 31 - JSP Introduction

Next Chapter: Chapter 33 - JSP Tags & XML

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.