CPAN423 Enterprise Java Programming

Lecture #3: An Introduction to JSP

JSP is a server side scripting language based on Java language with support for creating database driven application. It enables developers to insert Java code inside HTML pages to generate Dynamic Web sites. The extension of such files must be (.jsp) instead of (.html).

JSP pages are multi platform ,high level extension of servlets. They are finally compiled into a servlet by the JSP engine and loaded into the web server memory upon receiving the request to the JSP page for the first time. Subsequent calls to that page will be served faster.The compilation process happens once every time a new JSP page loaded.

javax.servlet.jsp package defines two interfaces: JSPPage and HttpJspPage. The JspPage interface is implemented by all jsp servlet classes. It has two methods: jspInit and jspDestroy. These methods are analogous to the init and destroy methods of the servlet.

The HttpJspPage interface extends the JspPage interface. It has one method _jspService. This method is called by the container to generate the content pf the jsp. We cannot include this method in the jsp. The page content represents this method. Programmer can define jspInit() and jspDestroy() methods, but the

_jspService(HttpServletRequest request,HttpServletResponse response)method is generated by the JSP engine.

The JspFactory class is an abstract class provides methods for obtaining other objects needed for the jsp page processing.

The JspEngineInfo abstract class provides info about the jsp engine. Only one method is available called getSpecificationVersion.

The abstract class PageContext provides methods used to create other objects. For example: getSession, getRequest,getResponse,getServletConfig, getServletContext

The JspWriter class is derived from the java.io.Writer class and represents a writer to send info to the client. Other methods allow you to manipulate the buffer.

The page object represents the HttpJspPage interface. The config object represent ServletConfig. pageContext represent the PageContext

JSP original style tags

There are four main tags in JSP:

1-Directive:
A JSP directive gives special information about the page to the JSP Engine.

Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page.

In the directives we can import packages, define error handling pages or the session information of the JSP page.

There are three main types of directives:

1-1 Page directive: defines attributes that apply to a JSP page. The following attribute appear in the page directive:

language: defines the language the file uses (currently always java). It has the syntax:

<%@ page language=”java” %>.

extends: defines the super class used by the JSP engine for the translated Servlet. It has the syntax:

<%@ page extends = “…” %>

import defines all the classes to be imported, separated by comma. For example

<%@ page import = “java.util.*,java.io.*” %>

session: Determines whether a session object will have to be defined, the default is true. For example:

<%@ page session = “false” %>

buffer: Controls the size of the response output buffer. The size can be none or a size, the default is 8kb.For example:

<%@ page buffer = “none” %>

autoFlash: Can be either true( the default) or false. If it is set to false an overflow of the buffer will causes an exception. If it is set to true the buffer will be flushed to the output stream when get full. This attribute must be set to false if buffet set to none. For example:

<%@ page autoFlush = “true” %>

isThreadSafe: Determine whether the generated servlet deal with multiple requests. It can be either true or false, the default is true. When set to false the JSP engine will allow only one request to be processed at any time. When true more than one request thread can run at the same time. For example:

<%@ page isThreadSafe="false" %>

The following code is note thread safe

<%! int i=0; %>

<%i=i+1 ;%>

To make it thread safe:

<%! int i=0; %>

<%

synchronize(this) {

i=i+1;

}

%>

Another example:

synchronized ( myVector)

{

myVector.removeElementAt(0);

}

By using synchronize(objectName) {} we indicate that no thread can access the code until the current one exits.

info: Defines a string value that can be accessed in the code using getServletInfo() method. Typiaclly used to add author information. For example:

<%@ page info = “ this is test page, copyright 2001. “ %>

errorPage: If present the value defines a URL of a resource that will be send any Exception or Error object that is not caught in the java code of the page. For example:

<%@ page errorPage = “error.jsp” %>

isErrorPage: If set to true the current page is the target of another page’s errorPage URL and the page has access to the implicit object exception. For example:

<%@ page isErrorPage = “true” %>

contentType:Set the MIME( multipurpose Internet media Extension) type and character set of the JSP page as used in the ServletResponse setContentType method. The default is “text/html:charset=ISO-8959-1”

<%@ page contentType = “text/html:charset=ISO-8959-1” %>

1-2 Include directive:

Allows a JSP developer to include contents of a file inside another. Typically include files are used for navigation, tables, headers and footers that are common to multiple pages. This file can be html, JSP or any thing else. for example:

<%@ include file="hello.jsp" %>

1-3 Taglib directive:

The taglib directive allows you to define a library of custom action tags that will be used in the page. Custom tags use interfaces and classes in the java.servlet.jsp.tagext package. It has the following syntax :

<%@ taglib uri = “tag library URI” prefix = “tag Prefix” %>

Each tag-library will have its own tag-library specific documentation. In order to use the tag library, you use the "taglib" directive to specify where your tag library's "description" resides.

2-Declarations
This tag is used for defining the functions and variables to be used in the JSP.
Declarations are found within the <%! ... %> tag. Always end variable declarations with a semicolon, as any content must be valid Java statements

Declarations do not generate output so are used with JSP expressions or scriptlets.

JSP declarations let you define page-level variables to save information or define supporting methods that the rest of a JSP page may need. For example:

<%! int i=0; public void someFunction(String arg)
{
// java code
}
%>

3-Scriplets

Between <% and %> tags, any valid Java code is called a Scriptlet. This code can access any variable or bean declared. The code is placed in _jspService method by the JSP engine.for example:

<%
// java codes
%>

You can mix scriptlets and HTML to make scriptlet generate HTML , for example :

<%! int i=0; %>
<%
if ( i==0 ) {
%>
<P>it is true
<%
} else {
%>
<P>it is false;
<%
}
%>

By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use “ out.println" inside the scriptlet as shown in the following example:

<%@ import="java.io.*,java.util.*" %>
<%
for (int i = 1; i < 6; i++)
{
out.println(i + "<BR>");
}
%>

4-Expressions
This tag allows the developer to embed any Java expression and is short for out.println(). A semicolon does not appear at the end of the code inside the tag.

We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.

Syntax of JSP Expressions are:

<%="Hello World" %>

Implicit Objects

The JSP container makes available implicit objects that can be used within scriptlets and expressions. These objects act as wrappers around underlying Java classes or interfaces typically defined within the Servlet API.

Note that these implicit objects are only visible within the system generated _jspService(HttpServletRequest request,HttpServletResponse response ) method. They are not visible within methods you define yourself in declarations.

There are four levels of objects scope:

Application: Objects accessible from pages that belong to the same application.

Session: Objects accessible from pages belonging to the same session as the one in which they where created

Request: Objects accessible from pages processing the request where they were created

Page: Objects accessible only within pages where they were created.

The implicit objects are:

1-page

page object is of type java.lang.Object and has page scope .It represents the current JSP page( synonym for the "this" operator).It is used to call any methods defined by the servlet class.

2-config

config object is of type javax.servlet.http.ServletConfig and has page scope. It represents the configuration data. It stores the servlet initialization parameter name value pairs and the servletContext object

3-request

request object is of type javax.servlet.http.httpservletrequest and has request scope. It represent the user request send through the browser to the server.

As a part of the request, various data is available, including the file the browser wants from the server, and if the request is coming from pressing a SUBMIT button, the information the user has entered in the form fields.

4-response

response object is of type javax.servlet.http.httpservletresponse and has page scope. It represent the output respond to the browser.

5-pageContext

pageContext object is of type javax.servlet.jsp.pagecontext and has page scope. It Contain attribute about the page

6-session

session object is of type javax.servlet.http.httpsession and has session scope. It contains arbitrary variables attached to the session user.

7-application

application object is of type javax.servlet.http.ServletContext and has application scope. It contains attribute for the entire application

8-out

out object is of type javax.servlet.jsp.JspWriter that writes into the output stream for the response. It has page scope.

9-exception

exception object is of type java.lang.Throwable .Only pages that are designated as error pages in the page directive have this object. It has page scope.

Comments in JSP

JSP allows for different styles of comments:

<%-- JSP style comment %> this comment will appear in the JSP page but it will be skipped by the JSP engine ,so it doesn’t appears in the resulting java code.

<% // java style comment // %> or <% /* java style comment */ %> this comment will appear in the JSP page and the resulting java code created by JSP engine but not in the output page.

<!-- HTML style comment --> ,this comment will be transmitted with the output page but not displayed.

A jsp:text element is used to enclose template data in the XML representation. The interpretation of a jsp:text element is to pass its content through to the current value of out For example:

<jsp:scriptlet>

I=0;

</jsp:scriptlet>

<jsp:text> This is a comment placed here </jsp:text>

<jsp:expression>I </jsp:expression>

The output would be

This is a comment placed here

Exception Handling

JSP provides a rather elegant mechanism for handling runtime exceptions. Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing. For example,

<%@ page isErrorPage="false" errorPage="errorHandler.jsp" %>

informs the JSP engine to forward any uncaught exception to the JSP page errorHandler.jsp. It is then necessary for errorHandler.jsp to flag itself as a error processing page using the directive:

<%@ page isErrorPage="true" %>

This allows the Throwable object describing the exception to be accessed within a scriptlet through the implicit exception object.

Integrating Servlets and JSP

To let a servlet forward request to a JSP we have to obtain a RequestDispatcher object by calling getRequestDispathcer method of ServletContext, supplying a URL relative to the servlet root. Once we have a requestDispatcher object we use forward method to completely transfer control to the associated URL.

Using JavaBeans with JSP

JavaBeans can be also used on the serve side. Following is a review of the requirement for a server side JavaBean class:

·  The class must be public, and must implement Serilizable interface.

·  The class must have a no argument constructor.

·  The class must provide public set and get methods to access private member variables of the bean class.

·  After you compile your class, you can use it in your JSP code, using the <jsp:useBeans /> tag. The place to put your javabean classes depends on the server you are running.

The bean scope attribute defines the accessibility and the life span of the bean. Page value indicate that the bean is available only in the current page after the point where the jsp:Bean is used. The request value indicates that the accessibility of the bean is extended to the forwarded and included pages. The session value indicates that the bean is placed in the session object and continues to exist as long as the session object is valid. The application value indicates that the bean lives through the life cycle of the jsp container itself.

We can use jsp:getProerpty and jsp:setProperty as follows:

<jsp:useBean id=”b1”/>

<jsp:setProperty name=”b1” property=”” value=”” />

jsp:Bean allows us to write code that will execute after the bean is initialized.

<jsp:useBean>

Some code

</jsp:useBean>

Examples

To run the following examples, refer to the deployment procedure described in lecture 2.

Ex1: greeting.jsp:

In this example we will show greeting message and the current date and time.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSP page</title>
</head>
<body>
<%!
java.util.Date date = new java.util.Date();
String message="Greeting from JSP";
%>
<%
out.println(message);
out.println("The time is now "+date);
%>
</body>
</html>
Here variables date and message will be declared once and the output will be the same for every request for the page..

The JSP file should be saved in the folder:

resin-x.x.x\webapps\cpan423

To invoke this JSP file from the deployment folder, type the following URL:

http://localhost:8080/cpan423/greeting.jsp