2013-09-24

Java Server Pages - Java Server Pages Overview, Overview of JSP Syntax Element, JSP Directives


Java Server Pages Overview

Structure of a JSP page

Directives

Scripting Elements

JSP Tags

Overview of JSP Syntax Element

Introduction

Directives

Scripting Elements

JSP Objects

Using an Implicit Object

Object Scopes

Standard Actions: JSP Tags

JSP Directives

Introduction

The JSP page Directive

The JSP include Directive

Example Using Scripting Elements and Directives

Java Server Pages Overview

 

Structure of a JSP page

 

If we rename a .php file to a .jsp file in that case that page is a applicable JSP page and will compile and run effectively. But this .jsp page will be by means of default features provided to a JSP page and will not be doing everything useful. One other thing to keep in mind is that all JSP pages are compiled to Java Servlet classes, so inherently JSP pages are actually Java Servlets.

 

A JSP page consists of following parts:

1. Directives
2. Scripting Elements
3. JSP Tags

 

 

 

Directives

 

Directives as its name implies are compile time organize tags. They permit us to modify how our JSP pages are compiled to Java Servlets.

 

There are three types of Directive:

1. Page Directive
2. Taglib Directive
3. Include Directive

 

The Page Directive

This directive is positioned at the top of a JSP page and allows you to customize different features of your JSP page.

 

It's syntax:

<%@ page attribute-name="value" %>

 

All JSP directives, scripting elements and expressions lie in between the <% and %> tags.

Following are the different attributes available to us along with the values we can use in our JSP page.

 

Attribute

Value

Description

language

scriptingLanguage

The language we are using on the JSP page. Default is Java.

extends

className

The Java class which our generated Servlet will be extending.

import

importList

A comma separated list of classes, interfaces and packages we want to use in our JSP page.

session

true | false

If we want to use session then set it to true, otherwise false. Default is true.

buffer

none | sizeInKB

Set it to none if we doesn't want to use buffering or set it to a value greater than 8KB. Default is 8KB.

autoFlush

true | false

If set to true, once buffer is full it will be sent to the client. If set to false then an exception will be generated on buffer overflow. Default is true.

isThreadSafe

true | false

If set to true then the JSP engine will send all the requests as they come to the same instance of the Servlet. If false then request will be sent to the Servlet one at a time. Default is true.

info

servletInfo

Returns info about the JSP page.

errorPage

pageURL

The URL to the JSP page where all un-handled exceptions will be sent.

isErrorPage

true | false

If this JSP page is the error page where other JSP page's un-handled exceptions will be sent then set it to true, otherwise false.

contentType

content/type

The content-type for the current JSP page. Default is text/html.

pageEncoding

encodingInfo

Character encoding for the JSP page. Default is ISO-8859-1.

 

 

The Taglib Directive

It is used to incorporate custom tags in a JSP page.

 

It requires two attributes and it's syntax is as :

<%@ taglib uri="tag-lib-uri" prefix="tag-prefix" %>

 

The uri attribute contains the location of the tag library TLD (Tag Library Descriptor) file, while prefix is the tag prefix you want to use for our custom tag e.g,

<%@ taglib uri="/WEB-INF/tlds/mytag.tld" prefix="star" %>
<star:time />

 

Above code describes a tag with prefix 'star' which displays current time.

 

 

The Include Directive

The include directive allows insertion of the content of another file into the JSP page at compilation time.

 

It's syntax is as follows :

<%@ include file="localOrAbsoluteURL" %>

 

During compilation the content of the file specified in the file attribute will be added to the current JSP page e.g,

... Some HTML and JSP code above

<%@ include file="/misc/mkdtutorials.txt" %>
</body>
</html>

 

Above code adds the mkdtutorials info to the current JSP page.

 

 

 

Scripting Elements

 

The scripting elements in a JSP page comprise of four types :

1. Comments
2. Class level declarations
3. Expression
4. Scriptlets

 

 

Comments

Like other Java classes we can add comments in a JSP page. Comments are useful as it makes your code more understandable.

 

The syntax of JSP comment is as follows:

<%-- This is a JSP Comment --%>

 

 

Class Level Declarations

This feature allows us to add our own class level methods and variables which can be accessed by the scriptlets.

 

It's syntax is as follows :

<%! Declaration Statement %>

 

For example :

<%! String author = "Aman Kumar"; %>

Above code declares a class level variable named author with a value of "Aman Kumar".

 

 

Expression

It is a short hand for writing output directly to the output stream.

 

Its syntax is as follows:

<%= statement %>

The value of the Java statement is displayed to the user. e.g,

<%= new java.util.Date().toString() %>

Above code displays the current date and time to the user.

 

 

Scriptlets

Within scriptlets we can add whatever Java code we like. All this code will go inside the _jspService() method, so we cannot declare class level methods or variables within scriptlets

 

It's syntax is as follows :

<% statements %>

For example:

<%
String name = "Aman Kumar";
out.println("My name is " + name);
%>

Above code first declares a name variable with value of "Aman Kumar" and then displays it to the user screen.

 

 

 

JSP Tags

 

As we saw earlier we can create and use our own custom tags inside a JSP page using the taglib directive. With that there are quite a few standard JSP tags which are part and parcel of the JSP specification and provide really useful functionality :

 

1. <jsp:include>
2. <jsp:forward>
3. <jsp:param>
4. <jsp:plugin>

 

The <jsp:include> Tag

This jsp:include tag allows inclusion of the content of the given file within the JSP page at the request time. It is different from the include directive we studied above where the content of the file was included at translation time.

 

It's syntax is as follows :

<jsp:include page="pathToFile" flush="true | false" />

 

The page attribute contains the path to the given file we want to include ( which can be a JSP page, Servlet or a simple HTML/text file ). In JSP compatible application servers (e.g, Tomcat 4.0) we can set the flush attribute to false.

 

The <jsp:param> Tag

This tag is used inside the <jsp:include>, <jsp:forward> and <jsp:plugin> tags.

It defines and sets different parameters with their values .e.g,

<jsp:include page="file.jsp" flush="true" %>
          <jsp:param name="name" value="Aman Kumar" />
</jsp:include>

 

In the code above a parameter with the name 'name' and a value of "Aman Kumar" has been provided to the included JSP page; file.jsp. The file.jsp page can access the value of this paramter by :

<%
      String name = request.getParamter("name");
%>

 

The <jsp:forward> Tag

This tag allows us to forward the control to a given page.

 

Its syntax is as follows:

<jsp:forward page="pathToFile" />

 

Where pathToFile is the path to the page we want control to be forwarded to.

Like <jsp:include> tag you can also use <jsp:param> to provide parameters to the forwarded page.

 

The <jsp:plugin> Tag

This tag allows us to embed Java applets or beans in a web page.

 

It's syntax is as follows :

<jsp:plugin type="bean | applet" code="className"
  codebase="path to root directory containing classes"
  align="top | middle | bottom | left | right"
  archives="jar files required for this app"
  height="height in pixels" width="width in pixels"
  hspace="horizontal space in pixels" vspace="vertical space"
  jreversion="the JRE version required"
  name="name of object"
  nspluginurl="URL for Netscape plugin"
  iepluginurl="URL For IE plugin">

<jsp:params>
      <jsp:param name="name" value="value" />
</jsp:params>

<jsp:fallback>
        Sorry your browser doesn't support Java applets.
</jsp:fallback>
</jsp:plugin>

 

Almost all the attributes for the <jsp:plugin> tag above are self explanatory.

 

 

 

Overview of JSP Syntax Element

 

Introduction

 

We saw a simple example of JSP .

Now here is a top-level list of syntax categories and topics:

 

1. directives --These convey information regarding the JSP page as a whole.

2. scripting elements--These are Java coding elements such as declarations, expressions, scriptlets, and comments.

3. objects and scopes--JSP objects can be created either explicitly or implicitly and are accessible within a given scope, such as from anywhere in the JSP page or the session.

4. actions--These create objects or affect the output stream in the JSP response (or both).

 

 

 

Directives

 

Directives provide instruction to the JSP container regarding the entire JSP page. This information is used in translating or executing the page. The basic syntax is as follows:

<%@ directive attribute1="value1" attribute2="value2"... %>

 

The JSP specification supports the following directives:

 

page:

Use this directive to specify any of a number of page-dependent attributes, such as scripting language, content type and character encoding, a class to extend, packages to import, an error page to use, the JSP page output buffer size, and whether to automatically flush the buffer when it is full.

 

For example:

<%@ page language="java" import="packages.mypackage" errorPage="boof.jsp" %>

or, to enable auto-flush and set the JSP page output buffer size to 20 KB:

<%@ page autoFlush="true" buffer="20kb" %>

or, to unbuffer the page:

<%@ page buffer="none" %>

 

Its limitations:

1. The default buffer size is 8 KB.
2. It is illegal to set autoFlush="true" when buffer="none".
3. A JSP page using an error page must be buffered. Forwarding to an error page (not outputting it to the browser) clears the buffer.
4. In the Oracle JSP implementation, "java" is the default language setting. It is good programming practice to set it explicitly, however. You can also use a "sqlj" setting for SQLJ JSP pages.
5. For information about using page directive attributes to set the content type and character set for the JSP page and response object..

 

include:

Use this directive to specify a resource that contains text or code to be inserted into the JSP page when it is translated.

 

For example:

<%@ include file="/jsp/userinfopage.jsp" %>

 

Notes:

1. The include directive, referred to as a "static include", is comparable in nature to the jsp:include action discussed later in this chapter, but jsp:include takes effect at request-time instead of translation-time.
2. The include directive can be used only between files in the same servlet context (application).

 

taglib:

We use this directive to specify a library of custom JSP tags that will be used in the JSP page. Vendors can extend JSP functionality with their own sets of tags. This directive includes a pointer to a tag library descriptor file and a prefix to distinguish use of tags from that library.

 

For example:

<%@ taglib uri="/oracustomtags" prefix="oracust" %>

 

 

 

Scripting Elements

 

JSP scripting elements include the following categories of Java code snippets that can appear in a JSP page:

 

.declarations--

These are statements declaring methods or member variables that will be used in the JSP page. A JSP declaration uses standard Java syntax within the <%!...%> declaration tags to declare a member variable or method. This will result in a corresponding declaration in the generated servlet code.

For example:

<%! double f1=0.0; %>

 

.expressions--

These are Java expressions that are evaluated, converted into string values as appropriate, and displayed where they are encountered on the page. A JSP expression does not end in a semicolon, and is contained within <%=...%> tags.

For example:

<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>

 

.scriptlets--

These are portions of Java code intermixed within the markup language of the page. A scriptlet, or code fragment, can consist of anything from a partial line to multiple lines of Java code. We can use them within the HTML code of a JSP page to set up conditional branches or a loop. A JSP scriptlet is contained within <%...%> scriptlet tags, using Java syntax.

For example:

<% if (pageBean.getNewName().equals("")) { %>
I don't know you.
<% } else { %>
Hello <%= pageBean.getNewName() %>.
<% } %>

 

.comments--

These are developer comments embedded within the JSP code, similar to comments embedded within any Java code. Comments are contained within <%--...--%> syntax.

For example:

<%-- Execute the following branch if no user name is entered. --%>

JSP comments are not visible when users view the page source from their browsers.

 

 

 

JSP Objects

 

The term JSP object refers to a Java class instance declared within or accessible to a JSP page.

 

JSP objects can be either:

.explicit--

Explicit objects are declared and created within the code of our JSP page, accessible to that page and other pages according to the scope setting us choose.

or

. implicit--

Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets or expressions in JSP pages according to the inherent scope setting of the particular object type.

 

 

Explicit Objects

Explicit objects are typically JavaBean instances that are declared and created in jsp:useBean action statements.

example:

<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

This statement defines an instance, pageBean, of the NameBean class that is in the mybeans package.

 

 

Implicit Objects

JSP technology makes available to any JSP page a set of implicit objects. These are Java objects that are created automatically by the JSP container and that allow interaction with the underlying servlet environment.

 

The following implicit objects are available:

. page

This is an instance of the JSP page implementation class and is created when the page is translated. The page implementation class implements the interface javax.servlet.jsp.HttpJspPage. Note that page is synonymous with this within a JSP page.

 

. request

This represents an HTTP request and is an instance of a class that implements the javax.servlet.http.HttpServletRequest interface, which extends the javax.servlet.ServletRequest interface.

 

. response

This represents an HTTP response and is an instance of a class that implements the javax.servlet.http.HttpServletResponse interface, which extends the javax.servlet.ServletResponse interface.
The response and request objects for a particular request are associated with each other.

 

. pageContext

This represents the page context of a JSP page, which is provided for storage and access of all page scope objects of a JSP page instance. A pageContext object is an instance of the javax.servlet.jsp.PageContext class.

The pageContext object has page scope, making it accessible only to the JSP page instance with which it is associated.

 

. session

This represents an HTTP session and is an instance of a class that implements the javax.servlet.http.HttpSession class.

 

. application

This represents the servlet context for the Web application and is an instance of the javax.servlet.ServletContext class.

The application object is accessible from any JSP page instance running as part of any instance of the application within a single JVM. (The programmer should be aware of the server architecture regarding use of JVMs.)

 

. out

This is an object that is used to write content to the output stream of a JSP page instance. It is an instance of the javax.servlet.jsp.JspWriter class, which extends the java.io.Writer class.

The out object is associated with the response object for a particular request.

 

. config

This represents the servlet configuration for a JSP page and is an instance of a class that implements the javax.servlet.ServletConfig interface. Generally speaking, servlet containers use ServletConfig instances to provide information to servlets during initialization. Part of this information is the appropriate ServletContext instance.

 

. exception

This implicit object applies only to JSP error pages--these are pages to which processing is forwarded when an exception is thrown from another JSP page. They must have the page directive isErrorPage attribute set to true.

The implicit exception object is a java.lang.Exception instance that represents the uncaught exception that was thrown from another JSP page and that resulted in the current error page being invoked. The exception object is accessible only from the JSP error page instance to which processing was forwarded when the exception was encountered.

 

 

Using an Implicit Object

 

The following example uses the request object to retrieve and display the value of the username parameter from the HTTP request:

<H3> Welcome <%= request.getParameter("username") %> ! <H3>

 

The request object, like the other implicit objects, is available automatically; it is not explicitly instantiated.

 

 

Object Scopes

 

Objects in a JSP page, whether explicit or implicit, are accessible within a particular scope.

In the case of explicit objects, such as a JavaBean instance created in a jsp:useBean action, we can explicitly set the scope with the following syntax, as in the example :

 

scope="scopevalue"

 

There are four possible scopes:

1. scope="page" (default scope):

The object is accessible only from within the JSP page where it was created. A page-scope object is stored in the implicit pageContext object. The page scope ends when the page stops executing.
Note that when the user refreshes the page while executing a JSP page, new instances will be created of all page-scope objects.

 

2. scope="request":

The object is accessible from any JSP page servicing the same HTTP request that is serviced by the JSP page that created the object. A request-scope object is stored in the implicit request object. The request scope ends at the conclusion of the HTTP request.

 

3. scope="session":

The object is accessible from any JSP page that is sharing the same HTTP session as the JSP page that created the object. A session-scope object is stored in the implicit session object. The session scope ends when the HTTP session times out or is invalidated.

 

4. scope="application":

The object is accessible from any JSP page that is used in the same Web application as the JSP page that created the object, within any single Java virtual machine. The concept is similar to that of a Java static variable. An application-scope object is stored in the implicit application servlet context object. The application scope ends when the application itself terminates, or when the JSP container or servlet container shuts down.

 

We can think of these four scopes as being in the following progression, from narrowest scope to broadest scope:

page < request < session < application

 

If we want to share an object between different pages in an application, such as when forwarding execution from one page to another, or including content from one page in another, we cannot use page scope for the shared object; in this case, there would be a separate object instance associated with each page. The narrowest scope we can use to share an object between pages is request.

 

 

 

Standard Actions: JSP Tags

 

JSP action elements result in some sort of action occurring while the JSP page is being executed, such as instantiating a Java object and making it available to the page.

 

Such actions may include the following:

1. creating a JavaBean instance and accessing its properties
2. forwarding execution to another HTML page, JSP page,
3. including an external resource in the JSP page

For standard actions, there is a set of tags defined in the JSP specification. Although directives and scripting elements described earlier in this chapter are sufficient to code a JSP page, the standard tags described here provide additional functionality and convenience

 

Here is the general tag syntax for JSP standard actions:

<jsp:tag attr1="value1" attr2="value2" ... attrN="valueN">
...body...
</jsp:tag>

or, where there is no body:

<jsp:tag attr1="value1", ..., attrN="valueN" />

 

The JSP specification includes the following standard action tags, which are introduced and briefly discussed here.

 

. jsp:useBean

The jsp:useBean tag accesses or creates an instance of a Java type, typically a JavaBean class, and associates the instance with a specified name, or ID. The key attributes are class, type, id, and scope

# Use the id attribute to specify the instance name. The JSP container will first search for an object by the specified ID, of the specified type, in the specified scope. If it does not exist, the container will attempt to create it.

 

# Intended use of the class attribute is to specify a class that can be instantiated.

 

# Intended use of the type attribute is to specify a type that cannot be instantiated by the JSP container--either an interface, an abstract class, or a class without a no-argument constructor.

 

# Use the scope attribute to specify the scope of the instance--either page for the instance to be associated with the page context object, request for it to be associated with the HTTP request object, session for it to be associated with the HTTP session object, or application for it to be associated with the servlet context.

 

There are three typical scenarios:

1. Use type and id to specify an instance that already exists in the target scope.
2. Use class and id to specify the name of an instance of the class, either an
    instance that already exists in the target scope, or an instance to be newly created by     the JSP container.
3. Use class, type, and id to specify a class to instantiate and a type to assign the
    instance to. In this case, the class must be legally assignable to the type.

 

Consider the following examples:

 

<jsp:useBean id="reqobj" type="mypkg.MyIntfc" scope="request" />

The preceding example uses a request-scope instance reqobj of type MyIntfc.

 

<jsp:useBean id="pageobj" class="mybeans.PageBean" scope="page" />

The preceding example uses a page-scope instance pageobj of class PageBean, first creating it if necessary.

 

<jsp:useBean id="sessobj" class="mybeans.SessionBean"
type="mypkg.MyIntfc scope="session" />

The preceding example creates an instance of class SessionBean, and assigns the instance to the variable sessobj of type MyIntfc.

 

. jsp:setProperty

The following example sets the user property of the pageBean instance to a value of "Smith":

<jsp:setProperty name="pageBean" property="user" value="Smith" />

 

The following example sets the user property of the pageBean instance according to the value set for a parameter called username in the HTTP request:

<jsp:setProperty name="pageBean" property="user" param="username" />

 

If the bean property and request parameter have the same name (user), we can simply set the property as follows:

<jsp:setProperty name="pageBean" property="user" />

 

The below example results in iteration over the HTTP request parameters, matching bean property names with request parameter names and setting bean property values according to the corresponding request parameter values.

<jsp:setProperty name="pageBean" property="*" />

 

 

. jsp:getProperty

The jsp:getProperty tag reads a bean property value, converts it to a Java string, and places the string value into the implicit out object so that it can be displayed as output. The bean must have been previously specified in a jsp:useBean tag. For the string conversion, primitive types are converted directly, and object types are converted using the toString() method specified in the java.lang.Object class.

 

The following example puts the value of the user property of the pageBean bean into the out object:

<jsp:getProperty name="pageBean" property="user" />

 

. jsp:param

We can use jsp:param tags in conjunction with jsp:include, jsp:forward, and jsp:plugin tags (described below).

 

Used with jsp:forward and jsp:include tags, a jsp:param tag optionally provides name/value pairs for parameter values in the HTTP request object. New parameters and values specified with this action are added to the request object, with new values taking precedence over old.

 

The following example sets the request object parameter username to a value of Smith:

<jsp:param name="username" value="Smith" />

 

. jsp:include

The jsp:include tag inserts additional static or dynamic resources into the page at request-time as the page is displayed. Specify the resource with a relative URL (either page-relative or application-relative).

 

For example:

<jsp:include page="/templates/userinfopage.jsp" flush="true" />

 

A "true" setting of the flush attribute results in the buffer being flushed to the browser when a jsp:include action is executed.

The JSP support either a "true" or "false" setting, with "false" being the default.

 

We can also have an action body with jsp:param tags, as shown in the following example:

<jsp:include page="/templates/userinfopage.jsp" flush="true" >
<jsp:param name="username" value="Smith" />
<jsp:param name="userempno" value="9876" />
</jsp:include>

 

. jsp:forward

The jsp:forward tag effectively terminates execution of the current page, discards its output, and dispatches a new page--either an HTML page, a JSP page.

 

Examples:

<jsp:forward page="/templates/userinfopage.jsp" />

or:

<jsp:forward page="/templates/userinfopage.jsp" >
<jsp:param name="username" value="Smith" />
<jsp:param name="userempno" value="9876" />
</jsp:forward>

 

. jsp:plugin

The jsp:plugin tag results in the execution of a specified applet or JavaBean in the client browser, preceded by a download of Java plugin software if necessary. Specify configuration information, such as the applet to run and the code base, using jsp:plugin attributes.

 

The following example shows the use of an applet plugin:

<jsp:plugin type=applet code="Molecule.class" codebase="/html" >
<jsp:params>
<jsp:param name="molecule" value="molecules/benzene.mol" />
</jsp:params>
<jsp:fallback>
<p> Unable to start the plugin. </p>
</jsp:fallback>
</jsp:plugin>

 

 

 

JSP Directives

Introduction

 

A JSP directive affects the overall structure of the servlet class.

 

It usually has the following form:

<%@ directive attribute="value" %>

 

However, we can also combine multiple attribute settings for a single directive, as follows:

<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>

 

There are two main types of directive:

1. Page: which lets us do things like import classes, customize the servlet superclass, and the like;

2. Include: which lets us insert a file into the servlet class at the time the JSP file is translated into a servlet.

 

 

 

The JSP page Directive

 

The page directive lets us define one or more of the following case-sensitive attributes:

 

. import="package.class"

or

import="package.class1,...,package.classN".

 

This lets us specify what packages should be imported.

 

For example:

<%@ page import="java.util.*" %>

The import attribute is the only one that is allowed to appear multiple times.

 

. contentType="MIME-Type"

or

contentType="MIME-Type;
charset=Character-Set"

This specifies the MIME type of the output. The default is text/html.

For example, the directive

<%@ page contentType="text/plain" %>

has the same effect as the scriptlet

<% response.setContentType("text/plain"); %>

 

. isThreadSafe="true|false".

A value of true (the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables.

A value of false indicates that the servlet should implement SingleThreadModel, with requests either delivered serially or with simultaneous requests being given separate servlet instances.

 

. session="true|false".

A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it.

A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.

 

. buffer="sizekb|none".

This specifies the buffer size for the JspWriter out. The default is server-specific, but must be at least 8kb.

 

. autoflush="true|false".

A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".

 

. extends="package.class".

This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.

 

. info="message".

This defines a string that can be retrieved via the getServletInfo method.

 

. errorPage="url".

This specifies a JSP page that should process any Throwables thrown but not caught in the current page.

 

. isErrorPage="true|false".

This indicates whether or not the current page can act as the error page for another JSP page. The default is false.

 

. language="java".

At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java is both the default and the only legal choice.

 

The XML syntax for defining directives is

<jsp:directive.directiveType attribute=value />

 

For example, the XML equivalent of :

<%@ page import="java.util.*" %>

is

<jsp:directive.page import="java.util.*" />

 

 

 

The JSP include Directive

 

The directive looks like this:

<%@ include file="relative url" %>

 

The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash.

The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.

 

For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site.

The include directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file.

 

Here's some representative code:

<HTML>

<HEAD>
<TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE>
<META NAME="author" CONTENT="webmaster@somesite.com">
<META NAME="keywords" CONTENT="...">
<META NAME="description" CONTENT="...">
<LINK REL=STYLESHEET
   HREF="Site-Styles.css"
   TYPE="text/css">
</HEAD>
<BODY>
<%@ include file="/navbar.php" %>

<!-- Part specific to this page ... -->

</BODY>
</HTML>

 

Note that since the include directive inserts the files at the time the page is translated, if the navigation bar changes, we need to re-translate all the JSP pages that refer to it.

 

This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and we want the inclusion process to be as efficient as possible. If, however, the included files changed more often, we could use the jsp:include action instead. This includes the file at the time the JSP page is requested.

 

 

 

Example Using Scripting Elements and Directives

 

Here is a simple example showing the use of JSP expressions, scriptlets, declarations, and directives:

 

<HTML>

<HEAD>

<TITLE>Learning and Using JavaServer Pages</TITLE>
<META NAME="author" CONTENT="MKDTutorials Tutorial Developer Team">
<META NAME="keywords"
   CONTENT="JSP,JavaServer Pages,servlets">
<META NAME="description"
  CONTENT="A quick example of the four main JSP tags.">
<LINK REL=STYLESHEET
   HREF="My-Style-Sheet.css"
   TYPE="text/css">
</HEAD>

<BODY BGCOLOR="#FDF006" TEXT="#123450" LINK="#0000EE"
  VLINK="#551A8B" ALINK="#FF0000">

<CENTER>
<TABLE BORDER=5 BGCOLOR="#008429">
<TR><TH CLASS="TITLE">
    Using JavaServer Pages</TABLE>
</CENTER>

<P>MKDTutorials show you some dynamic content created using various JSP mechanisms:</p>
<UL>
<LI><B>Expression.</B>
<BR>
    Your hostname: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B>
<BR>
<% out.println("Attached GET data: " +
     request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B>
<BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B>
<BR>
<%@ page import = "java.util.*" %>
   Current date: <%= new Date() %>
</UL>

</BODY>
</HTML>

 

Here's a typical result:

 

Output:



 

 

 

« Previous Next Chapter »

Show more