In the next four articles, we will look at JavaServer Pages (JSP). This article will cover the basics of creating a JPS page including templates, scripting elements as well as aspects such as directives and the lifecycle of a JSP. In the following articles we will look at JSP Pages using Expression Language, JSP Pages using Standard Actions, and JSP Pages using Tag Libraries. This is part of a series of articles to help you prepare for the web component developer exam.

What are JavaServer Pages

JavaServer Pages (JSP) is a Java technology enables you to easily combine regular, static HTML with dynamically generated content from servlets. It allows you to separate the presentation from the request processing and business logic. If you were to try and do this using a servlet, you would be required to mix, HTML code for the presentation with the Java code for request processing and business logic. With JSPs your web designer can write the regular HTML in the normal manner with their normal web page design tools and then add JSP elements to generate dynamic parts of the page content. , using familiar Web-page-building tools. The figure below demonstrates this:

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-separationofconcerns.jpg
Figure: Separation of request processing, presentation and business logic

This separation of concerns related to presentation, business logic and request processing between provides a number of advantages and benefits when compared with using servlets or compared to other technologies such as ASP, PHP or CGI. Also as JSP is now widely supported, it can be used on a wide number of platforms and web and application servers. Also with JSPs you still have access to all of the other functionality available from using Java technology including servlets.

The Structure of a JavaServer Page

The simplest way to understand a JavaServer Page is to provide an example of it. The listing below presents a relatively simple JavaServer Page.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-javaserverpages.jpg
Figure: JavaServer Page

As you can see, that for the most part it looks pretty much like standard HTML except for the JSP elements. There are three main types of JSP constructs that you embed in a page:
scripting elements used to specify Java code that will become part of the resultant servlet
directives allow you control the overall structure of the servlet
actions used to specify existing components that should be used and otherwise control the behavior of the JSP engine.
With scripting elements, there are a number of predefined variables that you can employ. There are also a number of elements standardized through the Java Standard Tag Library (JSTL) to reduce the complexity so that the web designer only needs to know how to use HTML template text and standard JSP elements like tags. The JSP page will then be converted automatically to a servlet where the static HTML is being printed to the output stream associated with the servlet’s service method.

JSP Lifecycle

When a JSP page is requested, the web container never outputs the content directly to the client. Instead the web container will transit the JSP page through the various stages of it’s lifecycle including translation and compilation before the web container returns a response to the client. There are four phases in the JSP lifecycle:
  • Translation
  • Initialization
  • Request Processing
  • Destruction

Below is the details of the phases.
Translation (Transform) - this is the first part of the translation process. The web container converts the jsp into a servlet code. In this servlet all of the template text like HTML is converted into println() statements and all of the JSP elements are converted to Java code for implementing the dynamic behaviour. Below is an example of the servlet generated from a JSP page.

Java Code: Example of servlet generated from JSP
package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class simpleJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
  ...
  public Object getDependants() {
    return _jspx_dependants;
  }
  public void _jspInit() {
     ...
  }
  public void _jspDestroy() {
     ...
  }
  
   public void _jspService(HttpServletRequest request,
   	HttpServletResponse response) throws java.io.IOException, ServletException {
    ...
  }
  ...
}
Translation(Compile) - this is the second part of the translation process. The servlet generated from the JSP is then compiled into a java class. If the container receives a subsequent request for the same JSP, it will check for changes to the JSP and start the translation process again if changes have been made. Otherwise it will load the servlet.

Initialization (Loading) - the web container will now load the newly created servlet class using the class loader. There is nothing special about this process. This is the standard process of the use of any java class.

Initialization (Instantiation) - this is done by calling the jspInit() method. This is done only once at the start of the initialization process. The initialization process will make both the ServletContext and ServletConfig objects available for accessing attributes for initializing resources, communicating with other servlets or with the web container. When initialization is completed, the servlet is ready to process requests.

Request Processing - once the initialization process is completed for the servlet, it is now available to process the incoming requests. Here the web container will invoke the servlet’s jspService() method to process the request. It receives as arguments an HttpServletRequest and HttpServletResponse objects. Once processing is completed, the response object is used to print the response in html or whatever format is required.

Destruction - this phase is when the web container shuts down the servlet by calling the jspDestroy() method. This happens when a JSP hasn’t been called after a period of time and the web container decides to remove an instance of a servlet from memory. or when the server needs memory, the server removes the instance of the servlet.

As the JSP has been transformed into a servlet, it benefits from all of the features for which servlets are known. This includes efficiency, integration, scalability, robustness, security as well as portability across platforms and vendor implementations of the specification. If there is a problem in the automatic translation process, precisely if you have an error in the dynamic portion of your JSP page, the system will not be able to properly translate it into a servlet. If your page has such a fatal translation-time error, the server will present an HTML error page describing the problem to the client. Although the process of making JavaServer Pages accessible on the Web is quite simple compared to that for servlets, your server still needs to be set up with access to the servlet and JSP class files and the Java compiler. Below is a figure showing the JSP lifecycle.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-jsplifecycle.jpg
Figure: JSP Lifecycle

Template Text

The majority of the JSP page that you create will consist of static HTML. In JSP’s this is known as template text. In general, it is like normal HTML with the same syntax rules. In a JSP, this text during the translation phase, is simply translated in the servlet which is generated from the JSP page into output using println() statements. You can create this text with any web page designer as you would any other page. There are only two exceptions to the “template text being passed straight through without any translation into println() statements. In the first when you want to have a <% in the output, you will need to put <\% in the template text. The second is when you want to have comments in your JSP page. In that case you will need to use the following for JSP comments:

XML Code: Syntax for JSP Comments
<%-JSP Comment --%>
Rather than the standard for HTML comments:

XML Code: Syntax for HTML Comments
<!-HTML Comment -->
Below is an example of using template text in a hello.jsp file:

XML Code: Example of Template Text
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body bgcolor="white">
    <h1>It’s me! I would like to call you ...</h1>
    <%-Calculate me 1 + 2 + 3 dynamically --%>
    1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />
  </body>
</html>
In this JSP, everything that is not a JSP element (i.e., directive, action or scripting element) is template text. As we mentioned before, all of the template text is sent to the browser as is. Because of this you can use JSP to generate output for not only HTML but XML, WML or plain text. The web container will treat any of template text in the same manner.

JSP Elements
In the next sections we we cover all of the elements that you can use to dynamically generate content in your JSP, starting with Scripting Elements.

Scripting Elements

JSP scripting elements allow you to add small pieces of Java code in a JSP page. This could be an if statement to generate variation of the content dependent on the condition. JSP containers will each have it’s own engine for scripting languages. For example if you are using Tomcat, you must use the JavaTM programming language for scripting, but other vendors’ JSP containers may include support for other scripting languages.There are three forms of scripting elements. They are shown in the table below.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-scriptingelements.jpg
Table: Scripting Element Forms

The declarations, expressions, and scriptlets all have a similar syntax and usage, but there are also some important differences. We will outline the similarities and differences using some examples.These are shown below:
Expressions (i.e. <%= and %> tags) these scripting elements can use any language expression that is considered valid in the page scripting language. You don’t use a semicolon at the end of the expression. This is shown with the examples below:
XML Code: Example of Scripting Elements using Expressions
<%= Math.sqrt(2) %> 
<%= myArray[i] %> 
<%= a + b + c %> 
<%= new java.util.Date() %>
What is considered a valid expression is dependent on the scripting language. If you use the Java language for scripting then you can use any valid Java Language expression between the expression tags. The expression’s parts are evaluated from left to right. A key difference between expressions and scriptlets is the lack of a semicolon within expression tags. This is the case even if you use the same expression within scriptlet tags where a semicolon is required.

Declarations (between <%! and %> tags) these scripting elements have one or more variable or method declarations that end or are separated by semicolons:
XML Code: Example of Scripting Elements using Declarations
<%! int x = 0; %> 
<%! int x, y; float z; %> 
<%! Shape a = new Shape(2,2); %>
The variable or method that you want to use must be declared in the JSP page before you can use it in the page. The scope of a declaration can be a JSP file or if the JSP file includes other files with the include directive, the scope is expanded to cover all of the included files.

Scriptlets (between <% and %> tags) these scripting elements allow you to write valid scripting language statements, like the following:
XML Code: Example of Scripting Elements using Scriptlets
<% 
    String firstName = null; 
    if (request.getParameter("firstName") == null) {
%>
As previously mentioned, with scriptlets, the end of a scripting language statement must end with a semicolon if required by the scripting language. With scriptlets, you can use any of the JSP implicit objects or classes imported via the page directive, declared in a declaration, or named using a <jsp:useBean> tag. An example of this is shown below with this JSP page that can be used for guessing a number. The listing is shown below:

XML Code: Example JSP using Scripting Elements
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="com.acme.numbergame.domain.NumberGuess"%>
<jsp:useBean id="numguess" class="com.acme.numbergame.domain.NumberGuess" scope="session" />
<jsp:setProperty name="numguess" property="*" />
<html>
<head>
<title>Number Guess</title>
</head>
<body bgcolor="white">
	<font size=4> <%
 	if (numguess.isSuccess()) {
 %> Congratulations!
		You have picked it after only <%=numguess.getNumGuesses()%> tries.
		<p>
			<%
				numguess.reset();
			%>
			Care to <a href="numguess.jsp">try again</a>?
			<%
				} else if (numguess.getNumGuesses() == 0) {
			%>
			Welcome to the Number Guess game.
		<p>I’m thinking of a number between 1 and 100.
		<p>
		<form method=get>
			What’s your guess? <input type=text name=guess> <input
				type=submit value="Submit">
		</form> <%
 	} else {
 %> Good guess, but no that isn't it. Try <b><%=numguess.getHint()%></b>.
		You have made <%=numguess.getNumGuesses()%> guesses.
		<p>I’m thinking of a number between 1 and 100.
		<p>
		<form method=get>
			What’s your guess? <input type=text name=guess> <input
				type=submit value="Submit">
		</form> <%
 	}
 %>
	</font>
</body>
</html>
The bean shown in the import statement at the top of the JSP page is shown below:
Java Code: Example of Bean used in JSP Page
import java.util.Random;

public class NumberGuess {
	int answer;
	boolean success;
	String hint;
	int numGuesses;

	public NumberGuess() {
		reset();
	}

	public boolean isSuccess() {
		return success;
	}

	public int getNumGuesses() {
		return numGuesses;
	}

	public void setGuess(String guess) {
		numGuesses++;
		int g;

		try {
			g = Integer.parseInt(guess);
		} catch (NumberFormatException e) {
			g = -1;
		}
		if (g == answer) {
			success = true;
		} else if (g == -1) {
			hint = "a number next time";
		} else if (g < answer) {
			hint = "higher";
		} else if (g > answer) {
			hint = "lower";
		}
	}

	public String getHint() {
		return hint;
	}
	
	public void reset() { 
		answer = Math.abs(new Random().nextInt() % 100) + 1; 
		success = false; 
		numGuesses = 0;
	}
}
In the above example, we are using Java as our scripting language, we have a large if then else statement in the JSP. The key difference is that the statements are written in HTML and JSP tags instead of Java. Between the <% %> tags, you can write as manly lines of scripting language statements as you require. Note that making a JSP page such as the one above, makes this difficult to reuse as well as reducing it’s portability.

Predefine Variables

To simplify the writing of JSP expressions and scriptlets, the JSP specification ensures that you are supplied with eight automatically defined variables know as implicit objects. These variables are not accessible in declarations because JSP declarations result in code that appears outside of the _jspService method. The available variables are request, response, out, session, application, config, pageContext, and page. The variables and their corresponding Java type are provided in the table below:

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-implicitjspobjects.jpg
Table: Implicit JSP Objects

The objects shown in provide in most cases, more information as the implicit variable in EL expression. This is detailed below:
  • pageContext contains a reference to an instance of the class named javax.servlet.jsp.PageContext. You have access to all methods for accessing references to all the other objects and attributes for holding data that is shared between components in the same page. This is the same object that you can access with the ${pageContext} EL expression. All attribute values for this object are page scoped; they are the same objects as are available to the EL world as a Map represented by the ${pageScope} expression.
  • request contains a reference to an instance of a class implementing the interface javax.servlet.http.HttpServletRequest. This class provides methods for accessing all the information about the current request (i.e. request parameters, attributes, headers, and cookies). This is the same object that you can access with the ${pageContext.request} EL expression. All attribute values for this object are request scope; they are the same objects as are available to the EL world as a Map represented by the ${requestScope} expression.
  • response contains a reference to an instance of a class implementing the interface object javax.servlet.http.HttpServletResponse. This class provides methods for accessing all the information about the current response as well as methods for setting headers and the status code, and adding cookies. This class also provides methods related to session tracking. The same object can be accessed with the ${pageContext.response} EL expression.
  • session contains a reference to an instance of a class that implements the javax.servlet.http.HttpSession interface. This class allows you access to the client's session data, managed by the server including when it was created and when a request for the session was last received. This is the same object that you can access with the ${pageContext.session} EL expression. All attribute values for this object are session scoped; they are the same objects as are available to the EL world as a Map represented by the ${sessionScope} expression.
  • application contains a reference to the instance of a class that implements the javax.servlet.ServletContext interface representing the application. This object holds references to application wide objects to which a user may require access. This includes things such as the database connection pool shared by all application users and log( ) methods that can be used to write messages to the container's log file. This is the same object that you can access with the ${pageContext.servletContext} EL expression. All attribute values for this object are application scoped; they are the same objects as are available to the EL world as a Map represented by the ${applicationScope} expression.
  • out is an instance of javax.servlet.jsp.JspWriter. You can use the print( ) and println( ) methods provided by this object to add text to the response message body. In general, this object is used for template text and JSP action elements instead of explicitly printing to the out object.
  • exception is available only in error pages and contains information about a runtime error. This the same object that you can access with the ${pageContext.exception} EL expression.
  • config contains a reference to a ServletConfig instance. The web container uses the ServletConfig to pass information to a servlet or JSP page during initialization. The configuration information contains initialization parameters defined in the deployment descriptor and the ServletContext object of the servlet or JSP in the web application.
  • page is assigned to the instance of the JSP implementation class, declared as an Object. You will in most likelihood never use this object. See Java documentation for more information.


JSP Action Elements

JSP Action elements are dynamic actions that are executed at runtime rather than during the translation phase for scripting elements. JSP Action elements are case sensitive, so be sure to use jsp:expression in lower case. The syntax is shown below:

XML Code: Syntax of JSP Action Elements
<jsp:expression attr1=”value1” attr2=”value2”>
Java Expression
</jsp:expression>
You can also use a shorthand expression if the action does not require a body. This is shown below:

XML Code: Syntax of JSP Action Elements
<jsp:expression attr1=”value1” attr2=”value2” />
These standard JSP actions are defined by the JSP specification and includes a number of elements that use XML syntax to specify various parameters. Below is an example of the firstName variable for the object manager being set:

[CODE=XML; Example of JSP Action Elements]<jsp:setProperty name="manager" property="firstName" value="Robert"/>

In many cases, attributes require that the value be a fixed string enclosed in either single or double quotes. In other case, the attributes allow you to use a JSP expression that is computed at request time. Below is another example of jsp:setProperty where the value of the attribute is being calculated at request time:

XML Code: Example of jsp:setProperty with calculated values
<jsp:setProperty name="simul" property="key" value=’<%= "key" + Math.random()%>’ />
Below is a table listing all of the standard JSP actions using the prefix jsp. As the prefix is pre-defined and the behaviour for all of these actions are found in the JSP specification, there is no need to declare standard actions using the taglib directive. All of these actions lists the attributes that permit a request-time value.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-attributesforjspexpressions.jpg
Table: Attributes that Permit JSP Expressions

JSP Standard Tag Library

The JSP Standard Tag Library (JSTL) is another set of JSP custom action elements that are available for you to use. Before the advent of JSTL, developers were required to develop custom actions even for generic tasks such as paging through a large data set. Because of this, there were significant number of custom tag libraries on the market providing duplication of functionality with varying degrees of quality. To eliminate this problem, a group of experienced tag library developers use the Java Community Process to define what's called the JSP Standard Tag Library. This is a set of libraries that group related actions. The list of actions are shown below:
  • Core conditional processing and looping, importing data from external sources, etc.
  • XML processing processing of XML data, such as transforming and accessing individual elements
  • Internationalization (I18N) and formatting format and parse localized information as well as insertion of localized information in a page
  • Relational database access (SQL) reading and writing relational database data
  • Functions a set of generic Expression Language functions


Below is an example of the use of JSTL:
XML Code: Example of JSTL in JSP
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<Strong> Sports Balls:</strong>
<br><br>
<table>
   <c:forEach var="ball" items="${balls}" >
       <tr>
	  <td> ${ball}</td>
       </tr>
   </c:forEach>
</table>
</body>
</html>
The <c:forEach> action in the listing is part of the JSTL core library. It provides a means to iterate over arrays and collections. We will look at the Expression Language in the next section.

The JSP Expression Language

Expression Language (EL) was introduced in JSTL 1.0 as a way of setting action attribute values based on runtime data from various sources. The EL specification of this language was later incorporated into the JSP 2.0 specification. This means that it can now be used in a portable manner for any tag library, as well as in other contexts than action attributes.

The EL is based on JavaScript and also XPath which is a language that is used to access pieces of an XML document. The key difference is that EL doesn’t blow up so easily if a variable has a value of null. As well it performs many data-type conversions automatically. This is quite useful in web applications where the input is often request parameters, which tend to be text value but which we need to manipulate as Boolean values or numbers. This makes for the need for a web application to be able to handle gracefully the absence of a parameter so important. EL is structured for this. Although EL provides many features, such as iterating over arrays and collections, one area that it doesn’t handle is the use of conditional statements. In JSPs, conditional statements are implemented as action elements. A simple example with a conditional EL is shown below:

XML Code: Example of conditional EL statement
<c:if test=”$(dataType eq ‘number’ }
   <c:out value="${30 + 90 + 300}" />
</c:if>
EL expressions always starts with the ${ delimiter (i.e. a dollar sign plus a left curly brace) and ends with } (i.e. a right curly brace). In your expression you can include numeric literals or other types of literals. You also have access to a set of implicit variables that provide access to request data, variables representing application data, and most operators that you're used to from other languages. An example of this is the such as the addition + sign used in the listing above.

EL expressions can also be used to assign values to action attributes marked as accepting a request-time attribute value. Before the advent of EL, these attribute values could only be assigned by Java expressions. This led to a common source of confusing syntax errors over the years. EL was therefore designed with simple syntax in order to help page authors with this task. As Expression Language is now part of the JSP specification, you can use EL expressions directly in the page. A simple example based on the previous listing that used the <c:out> action is shown below:

XML Code: Example of EL expression
30 + 90 + 300 = ${30 + 90+ 300}
This listing doesn’t mean the we no longer need the <c:out> action. In fact there are many situations where the <c:out> action is still useful. The literals that EL supports are numbers (e.g., 1 and 0.98), Booleans (true and false), strings (enclosed by double or single quotes), and the keyword null to represent the absence of a value. Below, we have listed the supported operators:

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-expressionlanguage.jpg
Table: List of Expression Language Operators

You can also have variables in EL expressions. This was shown in the listing above using the <c:if> action. The variable dataType was created in another part of the JSP using the <jsp:useBean> action. Variables are named references to objects created by the application or made available implicitly by the EL. You can also create custom actions or have them passed to your JSP page by a servlet. You can use every object that is available in one of the JSP scopes, as an EL variable. Below is the set of implicit EL variables that provide information about a request and other session or application information:

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-implicitelvariables.jpg
Table: List of Implicit EL variables

An example of an EL expression using variables are provided below. In this case, we have a <c:out> action with an EL expression using the implicit param variable to read the value of a request parameter named title:

XML Code: Example of &lt;c:out&gt; EL Expression use
<c:out value="${param.title}" />
The dot property accessor operator tells EL to look for the parameter name in the specified bean or collection. The name param is a collection of all request parameters, as shown in the above table. If the property name has any special characters, they must be in quotes and you must use the array accessor operator instead:

XML Code: Example of quote use in EL Expressions
 <c:out value="${param['book-title']}" />
A variable, action attributes and bean properties are always specific Java data types. The EL operators is dependent on type information in order to handle type conversions in the expected way. You don’t need to worry about this. For example if you are trying to do addition, EL will always try to convert any string in the expression to a number and do the addition.

JSP Directives

JSP directives affects the overall structure of the servlet that results from the JSP page. They are used to specify information about the page itself that in general will be the same across all requests for the page. The templates below show the two possible forms for directives. You can substitute single quotes for the double quotes around the attribute values, but you cannot omit completely the quotation marks. In order to obtain quote marks within an attribute value, precede them with a back slash, using \’ for ’ and \" for ".

XML Code: JSP directive syntax
<%@ directive attribute="value" %>
<%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %>
In JSP, there are three types of directives. We will go into detail about each of the directive types below.

Page Directive

This allows you to control the structure of the servlet generated by the JSP pages through the page-dependent attributes that can be defined. The page-dependent attributes that can be defined are shown in the table below.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-pagedirectiveattributes.jpg
Table: Page Directive Attribute

The syntax for page directives is shown below:
XML Code: Page Directive syntax
<%@ page [autoFlush="true |false"] [buffer="8kb |NN kb|none"]
  [contentType="mimeType "] [errorPage="pageOrContextRelativePath "]
  [extends="className "] [import="packageList "] [info="info "]
  [isELIgnored="true|false ] [isErrorPage="true|false "] 
  [isThreadSafe="true |false"] [language="java|language "] 
  [pageEncoding="encoding "] [session="true |false"]
%>
An example of the use of the page directive is the following:

XML Code: Example of Page Directive syntax
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ page import="java.util.*, java.math.*" %>
Include Directive

This allows you to insert a file into the servlet class at the time the JSP file is translated into a servlet. An include directive is always placed in the document at the point at which you need for the file to be inserted.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-includedirectiveattributes.jpg
Table: Include Directive Attributes

The syntax for include directives is shown below:

XML Code: Syntax of include directive
<%@ include file="pageOrContextRelativePath" %>
Taglib Directive

This directive is used to define custom markup tags. It declares that a JSP file is using custom tags, names the tag library that defines by them, and specifies the tag prefix.Below is a table outlining the different attributes for taglib directives.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-taglibdirectiveattribute.jpg
Table: Taglib Directive Attributes

The syntax for taglib directives is shown below:

XML Code: Syntax for Taglib Directive
<%@ taglib prefix="prefix" [uri="taglibURI" | tagdir="contextRelativePath"]%>
An example of a taglib directive is the following:

XML Code: Example of taglib directive
<%@ taglib uri="http://www.acme.com/tags" prefix="acm" %>
Attribute Directive

This directive declares attributes of custom actions defined in tag files. lets you specify properties for data objects and procedures.This directive is only used in tag files. The table below outlines the attributes for attribute directives.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-attributedirectiveattributes.jpg
Table: Attribute Directive Attributes

If you use the fragment attribute, then you cannot use the rtexprvalue and type attributes. As well a runtime expression value is alway accepted and the type is set to javax.servlet.jsp.tagext.JspFragment. The syntax for attribute directives is shown below:

XML Code: The Syntax of Attribute Directive
<%@ attribute name="attrName " 
  [description="description "] [required="true|false "]
  [fragment="true|false " | [type="attrDataType "] [rtexprvalue="true |false"]]
%>
An example of a tag directive is the following:

XML Code: Example of tag directive
<%@ attribute name="unitLoadDevice" required="true" %>
Tag Directive

This directive declares that the JSP file uses custom tags, specifies the tag library and defines their tag prefix. It is used only in tag files and defines the properties of the file itself, such as encoding, how to treat EL expressions and the properties of the custom actions for which the tag file implements the behavior. This information can be displayed in an authoring tool. The list of attributes are in the table below.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-tagdirectives.jpg
Table: Tag Directive Attributes

The syntax for tag directives is shown below:
XML Code: Syntax for Tag Directive
<%@ tag [body-content="empty|scriptless |tagdependent"]
  [description="description "] [display-name="displayName "]
  [dynamic-attributes="attrCollVar "] [example="example "]
  [import="packageList "] [isELIgnored="true|false "] [language="java |language "]
  [large-icon="largeIconPath "] [pageEncoding="encoding "]
  [small-icon="smallIconPath "]
%>
An example of a tag directive is the following:

XML Code: Example of Tag Directive
<%@ tag body-content="empty" dynamic-attributes="dynAttrs"%>
Variable Directives

This directive declares an expression language exposed by the tag to the calling page. It is used to declare variables in tag files and is analogous to the variable element in the Tag Library descriptor. The variable directive defines the details of a variable exposed by the tag handler to the calling page. A table showing the list of attributes is shown below.

Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam-a19-variabledirectiveattributes.jpg
Table: Variable Directive Attributes

The syntax for variable directives is shown below:

XML Code: Syntax for Variable Directive
<%@ variable name-given="attrAndVarName " | 
  name-from-attribute="attrName " alias="varName "
  [declare="true |false"] [description="description "]
  [scope="AT_BEGIN|AT_END|NESTED "] [variable-class="varType "]
%>
An example of the use of the variable directive is the following:

XML Code: Example of Variable Directive
<%@ variable name-from-attribute="var" alias="random" 
  variable-class="java.math.Random" scope="AT_END" %>
<%@ attribute name="random" required="true" rtexprvalue="false" %>
That’s it for a review of Java Server Pages. In the next article in this series on JSP we will look at building JSP pages using the expression language.