0% found this document useful (0 votes)
29 views56 pages

BCA AWT Unit 5

Uploaded by

bhardwaj202136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views56 pages

BCA AWT Unit 5

Uploaded by

bhardwaj202136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

BCA

Advanced Web Technology


JSP Unit 5
Introduction to JSP
JSP technology is used to create web application just like Servlet
technology. It can be thought of as an extension to Servlet because it
provides more functionality than servlet such as expression language,
JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and
development. It provides some additional features such as Expression
Language, Custom Tags, etc.

Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes
JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business
logic with presentation logic. In Servlet technology, we mix our business
logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the


project. The Servlet code needs to be updated and recompiled if we have
to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc.
that reduces the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page

o Classloading (the classloader loads class file)

o Instantiation (Object of the Generated Servlet is created).

o Initialization ( the container invokes jspInit() method).

o Request processing ( the container invokes _jspService() method).

o Destroy ( the container invokes jspDestroy() method).

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and
save it by .jsp extension. We have saved this file as index. jsp. Put it in a
folder and paste the folder in the web-apps directory in apache tomcat to
run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to
put Java code in the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>

3. <% out.print(2*5); %>

4. </body>

5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server

o Put the JSP file in a folder and deploy on the server

o Visit the browser by the URL


http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP
page outside the WEB-INF folder or in any directory.
Comparison with Servlet

Brief Introduction: Servlet technology is used to create a web


application. A servlet is a Java class that is used to extend the
capabilities of servers that host applications accessed by means of a
request-response model. Servlets are mainly used to extend the
applications hosted by web services.

JSP is used to create web applications just like Servlet technology.


A JSP is a text document that contains two types of text: static data
and dynamic data. The static data can be expressed in any text-based
format (like HTML, XML, SVG, and WML), and the dynamic content can
be expressed by JSP elements. Difference between Servlet and JSP

The difference between Servlet and JSP is as follows:

Servlet JSP

Servlet is a java code. JSP is a HTML-based


Servlet JSP

compilation code.

Writing code for servlet is


JSP is easy to code as it is java
harder than JSP as it is HTML in
in HTML.
java.

Servlet plays a controller role in JSP is the view in the MVC


the ,MVC approach. approach for showing output.

JSP is slower than Servlet


because the first step in the JSP
Servlet is faster than JSP. lifecycle is the translation of
JSP to java code and then
compile.

Servlet can accept all protocol JSP only accepts HTTP


requests. requests.

In Servlet, we can override the In JSP, we cannot override its


service() method. service() method.

In Servlet by default session


In JSP session management is
management is not enabled,
automatically enabled.
user have to enable it explicitly.

In Servlet we have to In JSP business logic is


implement everything like separated from presentation
business logic and presentation logic by using JavaBeansclient-
logic in just one servlet file. side.

Modification in Servlet is a JSP modification is fast, just


time-consuming compiling task need to click the refresh
because it includes reloading,
Servlet JSP

recompiling, JavaBeans and


button.
restarting the server.

It does not have inbuilt implicit In JSP there are inbuilt implicit
objects. objects.

There is no method for running While running the JavaScript at


JavaScript on the client side in the client side in JSP, client-
Servlet. side validation is used.

Packages can be imported into


Packages are to be imported on
the JSP program (i.e, bottom ,
the top of the program.
middleclient-side, or top )

It can handle extensive data It cannot handle extensive data


processing. processing very efficiently.

The facility of writing custom The facility of writing custom


tags is not present. tags is present.

Before the execution, JSP is


Servlets are hosted and compiled in Java Servlets and
executed on Web Servers. then it has a similar lifecycle as
Servlets.

JSP Architecture
JSP architecture gives a high-level view of the working of JSP. JSP
architecture is a 3 tier architecture. It has a Client, Web Server, and
Database. The client is the web browser or application on the user side.
Web Server uses a JSP Engine i.e; a container that processes JSP. For
example, Apache Tomcat has a built-in JSP Engine. JSP Engine
intercepts the request for JSP and provides the runtime environment for
the understanding and processing of JSP files. It reads, parses, build
Java Servlet, Compiles and Executes Java code, and returns the HTML
page to the client. The webserver has access to the Database. The
following diagram shows the architecture of JSP.

Step 1: The client navigates to a file ending with the .jsp


extension and the browser initiates an HTTP request to the webserver.
For example, the user enters the login details and submits the button.
The browser requests a status.jsp page from the webserver.

Step 2: If the compiled version of JSP exists in the web server, it


returns the file. Otherwise, the request is forwarded to the JSP Engine.
This is done by recognizing the URL ending with .jsp extension.

Step 3: The JSP Engine loads the JSP file and translates the JSP to
Servlet(Java code). This is done by converting all the template text into
println() statements and JSP elements to Java code. This process is
called translation.

Step 4: The JSP engine compiles the Servlet to an


executable .class file. It is forwarded to the Servlet engine. This
process is called compilation or request processing phase.

Step 5: The .class file is executed by the Servlet engine which is a


part of the Web Server. The output is an HTML file. The Servlet engine
passes the output as an HTTP response to the webserver.

Step 6: The web server forwards the HTML file to the client’s browser.

JSP Scripting Elements


JSP Scripting elements
The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:

o scriptlet tag

o expression tag

o declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as


follows:

1. <% java source code %>

Example of JSP scriptlet tag

In this example, we are displaying a welcome message.

1. <html>

2. <body>

3. <% out.print("welcome to jsp"); %>

4. </body>

5. </html>

Example of JSP scriptlet tag that prints the user name

In this example, we have created two files index.html and welcome.jsp.


The index.html file gets the username from the user and the
welcome.jsp file prints the username with the welcome message.

File: index.html

1. <html>

2. <body>

3. <form action="welcome.jsp">

4. <input type="text" name="uname">

5. <input type="submit" value="go"><br/>

6. </form>

7. </body>

8. </html>
1. <html>

2. <body>

3. <%

4. String name=request.getParameter("uname");

5. out.print("welcome "+name);

6. %>

7. </form>

8. </body>

9. </html>

JSP expression tag

The code placed within JSP expression tag is written to the output
stream of the response. So you need not write out.print() to write data.
It is mainly used to print the values of variable or method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a


welcome message.

1. <html>

2. <body>

3. <%= "welcome to jsp" %>

4. </body>

5. </html>

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar
class. The getTime() is an instance method of Calendar class, so we have
called it after getting the instance of Calendar class by the getInstance()
method.

index.jsp
1. <html>

2. <body>

3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>

4. </body>

5. </html>

Example of JSP expression tag that prints the user name

In this example, we are printing the username using the expression tag.
The index.html file gets the username and sends the request to the
welcome.jsp file, which displays the username.

File: index.jsp

1. <html>

2. <body>

3. <form action="welcome.jsp">

4. <input type="text" name="uname"><br/>

5. <input type="submit" value="go">

6. </form>

7. </body>

8. </html>

File: welcome.jsp

1. <html>

2. <body>

3. <%= "Welcome "+request.getParameter("uname") %>

4. </body>

5. </html>

JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the
service() method of auto generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and
printing the value of the declared field using the jsp expression tag.

index.jsp

1. <html>

2. <body>

3. <%! int data=50; %>

4. <%= "Value of the variable is:"+data %>

5. </body>

6. </html>

Example of JSP declaration tag that declares method

In this example of JSP declaration tag, we are defining the method which
returns the cube of given number and calling this method from the jsp
expression tag. But we can also use jsp scriptlet tag to call the declared
method.

index.jsp

1. <html>

2. <body>

3. <%!

4. int cube(int n){

5. return n*n*n*;

6. }

7. %>

8. <%= "Cube of 3 is:"+cube(3) %>

9. </body>

10. </html>

JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually
has the following form −
<%@ directive attribute = "value" %>

Directives can have a number of attributes which you can list down as
key-value pairs and separated by commas.

The blanks between the @ symbol and the directive name, and between
the last attribute and the closing %>, are optional.

There are three types of directive tag −

S.No. Directive & Description

<%@ page ... %>


1 Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements.

<%@ include ... %>


2
Includes a file during the translation phase.

<%@ taglib ... %>


3 Declares a tag library, containing custom actions, used in the
page

JSP - The page Directive

The page directive is used to provide instructions to the container. These


instructions pertain to the current JSP page. You may code page directives
anywhere in your JSP page. By convention, page directives are coded at
the top of the JSP page.

Following is the basic syntax of the page directive −

<%@ page attribute = "value" %>

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.page attribute = "value" />

Attributes

Following table lists out the attributes associated with the page directive

S.No. Attribute & Purpose

1 buffer
Specifies a buffering model for the output stream.

autoFlush
2
Controls the behavior of the servlet output buffer.

contentType
3
Defines the character encoding scheme.

errorPage
4 Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.

isErrorPage
5 Indicates if this JSP page is a URL specified by another JSP
page's errorPage attribute.

extends
6
Specifies a superclass that the generated servlet must extend.

import
7 Specifies a list of packages or classes for use in the JSP as the
Java import statement does for Java classes.

info
8 Defines a string that can be accessed with the
servlet's getServletInfo() method.

isThreadSafe
9
Defines the threading model for the generated servlet.

language
10
Defines the programming language used in the JSP page.

11 session
Specifies whether or not the JSP page participates in HTTP
sessions

isELIgnored
12 Specifies whether or not the EL expression within the JSP page
will be ignored.

isScriptingEnabled
13
Determines if the scripting elements are allowed for use.

The include Directive

The include directive is used to include a file during the translation


phase. This directive tells the container to merge the content of other
external files with the current JSP during the translation phase. You may
code the include directives anywhere in your JSP page.

The general usage form of this directive is as follows −

<%@ include file = "relative url" >

The filename in the include directive is actually a relative URL. If you just
specify a filename with no associated path, the JSP compiler assumes that
the file is in the same directory as your JSP.

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.include file = "relative url" />

The taglib Directive

The JavaServer Pages API allow you to define custom JSP tags that look
like HTML or XML tags and a tag library is a set of user-defined tags that
implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom
tags, identifies the location of the library, and provides means for
identifying the custom tags in your JSP page.

The taglib directive follows the syntax given below −

<%@ taglib uri="uri" prefix = "prefixOfTag" >

Here, the uri attribute value resolves to a location the container


understands and the prefix attribute informs a container what bits of
markup are custom actions.
You can write the XML equivalent of the above syntax as follows −

<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />

JSP - Actions

These actions use constructs in XML syntax to control the behavior of the
servlet engine. You can dynamically insert a file, reuse JavaBeans
components, forward the user to another page, or generate HTML for the
Java plugin.

There is only one syntax for the Action element, as it conforms to the XML
standard −

<jsp:action_name attribute = "value" />

Action elements are basically predefined functions. The following table


lists out the available JSP actions −

S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or
EMBED tag for the Java plugin.

7 jsp:element
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.

Common Attributes

There are two attributes that are common to all Action elements:
the idattribute and the scope attribute.

Id attribute

The id attribute uniquely identifies the Action element, and allows the
action to be referenced inside the JSP page. If the Action creates an
instance of an object, the id value can be used to reference it through the
implicit object PageContext.

Scope attribute

This attribute identifies the lifecycle of the Action element. The id attribute
and the scope attribute are directly related, as the scope attribute
determines the lifespan of the object associated with the id. The scope
attribute has four possible values: (a) page, (b)request, (c)session,
and (d) application.

The <jsp:include> Action

This action lets you insert files into the page being generated. The syntax
looks like this −

<jsp:include page = "relative URL" flush = "true" />

Unlike the include directive, which inserts the file at the time the JSP
page is translated into a servlet, this action inserts the file at the time the
page is requested.

Following table lists out the attributes associated with the include action −
S.No. Attribute & Description

page
1
The relative URL of the page to be included.

flush
2 The boolean attribute determines whether the included
resource has its buffer flushed before it is included.

Example

Let us define the following two files (a)date.jsp and (b) main.jsp as
follows −

Following is the content of the date.jsp file −

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −

<html>

<head>

<title>The include Action Example</title>

</head>

<body>

<center>

<h2>The include action Example</h2>

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

</center>

</body>

</html>

Let us now keep all these files in the root directory and try to
access main.jsp. You will receive the following output −

The <jsp:useBean> Action


The useBean action is quite versatile. It first searches for an existing
object utilizing the id and scope variables. If an object is not found, it then
tries to create the specified object.

The simplest way to load a bean is as follows −

<jsp:useBean id = "name" class = "package.class" />

Once a bean class is loaded, you can


use jsp:setProperty and jsp:getProperty actions to modify and retrieve
the bean properties.

Following table lists out the attributes associated with the useBean action

S.No. Attribute & Description

class
1
Designates the full package name of the bean.

type
2
Specifies the type of the variable that will refer to the object.

beanName
3 Gives the name of the bean as specified by the instantiate ()
method of the java.beans.Beans class.

Let us now discuss the jsp:setProperty and the jsp:getPropertyactions


before giving a valid example related to these actions.

The <jsp:setProperty> Action

The setProperty action sets the properties of a Bean. The Bean must
have been previously defined before this action. There are two basic ways
to use the setProperty action −

You can use jsp:setProperty after, but outside of


a jsp:useBeanelement, as given below −

<jsp:useBean id = "myName" ... />

...

<jsp:setProperty name = "myName" property = "someProperty" .../>

In this case, the jsp:setProperty is executed regardless of whether a


new bean was instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of
a jsp:useBean element, as given below −

<jsp:useBean id = "myName" ... >

...

<jsp:setProperty name = "myName" property = "someProperty" .../>

</jsp:useBean>

Here, the jsp:setProperty is executed only if a new object was instantiated,


not if an existing one was found.

Following table lists out the attributes associated with


the setPropertyaction −

S.No. Attribute & Description

name
1 Designates the bean the property of which will be set. The
Bean must have been previously defined.

property

Indicates the property you want to set. A value of "*" means


2 that all request parameters whose names match bean
property names will be passed to the appropriate setter
methods.

value

3 The value that is to be assigned to the given property. The the


parameter's value is null, or the parameter does not exist, the
setProperty action is ignored.

param

4 The param attribute is the name of the request parameter


whose value the property is to receive. You can't use both
value and param, but it is permissible to use neither.

The <jsp:getProperty> Action


The getProperty action is used to retrieve the value of a given property
and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required.
The syntax of the getProperty action is as follows −

<jsp:useBean id = "myName" ... />

...

<jsp:getProperty name = "myName" property = "someProperty" .../>

Following table lists out the required attributes associated with


the getProperty action −

S.No. Attribute & Description

name
1 The name of the Bean that has a property to be retrieved. The
Bean must have been previously defined.

property
2 The property attribute is the name of the Bean property to be
retrieved.

Example

Let us define a test bean that will further be used in our example −

/* File: TestBean.java */

package action;

public class TestBean {

private String message = "No message specified";

public String getMessage() {

return(message);

public void setMessage(String message) {

this.message = message;
}

Compile the above code to the generated TestBean.class file and make
sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\
webapps\WEB-INF\classes\action folder and the CLASSPATH variable
should also be set to this folder −

Now use the following code in main.jsp file. This loads the bean and
sets/gets a simple String parameter −

<html>

<head>

<title>Using JavaBeans in JSP</title>

</head>

<body>

<center>

<h2>Using JavaBeans in JSP</h2>

<jsp:useBean id = "test" class = "action.TestBean" />

<jsp:setProperty name = "test" property = "message"

value = "Hello JSP..." />

<p>Got message....</p>

<jsp:getProperty name = "test" property = "message" />

</center>

</body>

</html>

The <jsp:forward> Action

The forward action terminates the action of the current page and
forwards the request to another resource such as a static page, another
JSP page, or a Java Servlet.

Following is the syntax of the forward action −


<jsp:forward page = "Relative URL" />

Following table lists out the required attributes associated with the
forward action −

S.No. Attribute & Description

page
1 Should consist of a relative URL of another resource such as a
static page, another JSP page, or a Java Servlet.

Example

Let us reuse the following two files (a) date.jsp and (b) main.jsp as
follows −

Following is the content of the date.jsp file −

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −

<html>

<head>

<title>The include Action Example</title>

</head>

<body>

<center>

<h2>The include action Example</h2>

<jsp:forward page = "date.jsp" />

</center>

</body>

</html>

Let us now keep all these files in the root directory and try to
access main.jsp. This would display result something like as below.

Here it discarded the content from the main page and displayed the
content from forwarded page only.

The <jsp:plugin> Action


The plugin action is used to insert Java components into a JSP page. It
determines the type of browser and inserts
the <object> or <embed>tags as needed.

If the needed plugin is not present, it downloads the plugin and then
executes the Java component. The Java component can be either an
Applet or a JavaBean.

The plugin action has several attributes that correspond to common HTML
tags used to format Java components. The <param> element can also be
used to send parameters to the Applet or Bean.

Following is the typical syntax of using the plugin action −

<jsp:plugin type = "applet" codebase = "dirname" code =


"MyApplet.class"

width = "60" height = "80">

<jsp:param name = "fontcolor" value = "red" />

<jsp:param name = "background" value = "black" />

<jsp:fallback>

Unable to initialize Java Plugin

</jsp:fallback>

</jsp:plugin>

JSP Implicit Objects


we will discuss the Implicit Objects in JSP. These Objects are the Java
objects that the JSP Container makes available to the developers in each
page and the developer can call them directly without being explicitly
declared. JSP Implicit Objects are also called pre-defined variables.

Following table lists out the nine Implicit Objects that JSP supports −

S.No. Object & Description

1 request
This is the HttpServletRequest object associated with the
request.

response
2 This is the HttpServletResponse object associated with the
response to the client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5 This is the ServletContext object associated with the
application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.

Exception
9 The Exception object allows the exception data to be accessed
by designated JSP.

The request Object

The request object is an instance of


a javax.servlet.http.HttpServletRequest object. Each time a client requests
a page the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.

The response Object

The response object is an instance of


a javax.servlet.http.HttpServletResponse object. Just as the server creates
the request object, it also creates an object to represent the response to
the client.

The response object also defines the interfaces that deal with creating
new HTTP headers. Through this object the JSP programmer can add new
cookies or date stamps, HTTP status codes, etc.

The out Object

The out implicit object is an instance of a javax.servlet.jsp.JspWriterobject


and is used to send content in a response.

The initial JspWriter object is instantiated differently depending on


whether the page is buffered or not. Buffering can be easily turned off by
using the buffered = 'false' attribute of the page directive.

The JspWriter object contains most of the same methods as


the java.io.PrintWriter class. However, JspWriter has some additional
methods designed to deal with buffering. Unlike the PrintWriter object,
JspWriter throws IOExceptions.

Following table lists out the important methods that we will use to
write boolean char, int, double, object, String, etc.

S.No. Method & Description

out.print(dataType dt)
1
Print a data type value

out.println(dataType dt)
2 Print a data type value then terminate the line with new line
character.

out.flush()
3
Flush the stream.

The session Object


The session object is an instance of javax.servlet.http.HttpSessionand
behaves exactly the same way that session objects behave under Java
Servlets.

The session object is used to track client session between client requests

The application Object

The application object is direct wrapper around the ServletContextobject


for the generated Servlet and in reality an instance of
a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle.
This object is created when the JSP page is initialized and will be removed
when the JSP page is removed by the jspDestroy()method.

By adding an attribute to application, you can ensure that all JSP files that
make up your web application have access to it.

The config Object

The config object is an instantiation of javax.servlet.ServletConfigand is a


direct wrapper around the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine
initialization parameters such as the paths or file locations etc.

The following config method is the only one you might ever use, and its
usage is trivial −

config.getServletName();

This returns the servlet name, which is the string contained in


the <servlet-name> element defined in the WEB-INF\web.xml file.

The pageContext Object

The pageContext object is an instance of


a javax.servlet.jsp.PageContext object. The pageContext object is used to
represent the entire JSP page.

This object is intended as a means to access information about the page


while avoiding most of the implementation details.

This object stores references to the request and response objects for each
request. The application, config, session, and out objects are derived by
accessing attributes of this object.

The pageContext object also contains information about the directives


issued to the JSP page, including the buffering information, the
errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE,
REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which
identify the four scopes. It also supports more than 40 methods, about
half of which are inherited from the javax.servlet.jsp.JspContext class.

One of the important methods is removeAttribute. This method accepts


either one or two arguments. For example, pageContext.removeAttribute
("attrName") removes the attribute from all scopes, while the following
code only removes it from the page scope −

pageContext.removeAttribute("attrName", PAGE_SCOPE);

The page Object

This object is an actual reference to the instance of the page. It can be


thought of as an object that represents the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object

The exception object is a wrapper containing the exception thrown from


the previous page. It is typically used to generate an appropriate response
to the error condition.

JSP Expression Language


JSP Expression Language (EL) makes it possible to easily access
application data stored in JavaBeans components. JSP EL allows
you to create expressions both (a) arithmetic and (b) logical.
Within a JSP EL expression, you can use integers, floating point
numbers, strings, the built-in constants true and false for boolean
values, and null.

Simple Syntax

Typically, when you specify an attribute value in a JSP tag, you


simply use a string. For example −

<jsp:setProperty name = "box" property = "perimeter" value =


"100"/>

JSP EL allows you to specify an expression for any of these


attribute values. A simple syntax for JSP EL is as follows −

${expr}

Here expr specifies the expression itself. The most common


operators in JSP EL are . and []. These two operators allow you to
access various attributes of Java Beans and built-in JSP objects.
For example, the above syntax <jsp:setProperty> tag can be
written with an expression like −

<jsp:setProperty name = "box" property = "perimeter"

value = "${2*box.width+2*box.height}"/>

When the JSP compiler sees the ${} form in an attribute, it


generates code to evaluate the expression and substitues the
value of expresson.

You can also use the JSP EL expressions within template text for a
tag. For example, the <jsp:text> tag simply inserts its content
within the body of a JSP. The following <jsp:text> declaration
inserts <h1>Hello JSP!</h1> into the JSP output −

<jsp:text>

<h1>Hello JSP!</h1>

</jsp:text>

You can now include a JSP EL expression in the body of


a <jsp:text>tag (or any other tag) with the same ${} syntax you
use for attributes. For example −

<jsp:text>

Box Perimeter is: ${2*box.width + 2*box.height}

</jsp:text>

EL expressions can use parentheses to group subexpressions. For


example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7.

To deactivate the evaluation of EL expressions, we specify


the isELIgnored attribute of the page directive as below −

<%@ page isELIgnored = "true|false" %>

The valid values of this attribute are true and false. If it is true,
EL expressions are ignored when they appear in static text or tag
attributes. If it is false, EL expressions are evaluated by the
container.

Basic Operators in EL

JSP Expression Language (EL) supports most of the arithmetic and


logical operators supported by Java. Following table lists out the
most frequently used operators −
S.No. Operator & Description

.
1
Access a bean property or Map entry

[]
2
Access an array or List element

()
3
Group a subexpression to change the evaluation order

+
4
Addition

-
5
Subtraction or negation of a value

*
6
Multiplication

/ or div
7
Division

% or mod
8
Modulo (remainder)

== or eq
9
Test for equality

!= or ne
10
Test for inequality

< or lt
11
Test for less than
> or gt
12
Test for greater than

<= or le
13
Test for less than or equal

>= or ge
14
Test for greater than or equal

&& or and
15
Test for logical AND

|| or or
16
Test for logical OR

! or not
17
Unary Boolean complement

empty
18
Test for empty variable values

Explore our latest online courses and learn new skills at your own
pace. Enroll and become a certified expert to boost your career.

Functions in JSP EL

JSP EL allows you to use functions in expressions as well. These


functions must be defined in the custom tag libraries. A function
usage has the following syntax −

${ns:func(param1, param2, ...)}

Where ns is the namespace of the function, func is the name of


the function and param1 is the first parameter value. For
example, the function fn:length, which is part of the JSTL library.
This function can be used as follows to get the length of a string.
${fn:length("Get my length")}

To use a function from any tag library (standard or custom), you


must install that library on your server and must include the
library in your JSP using the <taglib> directive as explained in the
JSTL chapter.

JSP EL Implicit Objects

The JSP expression language supports the following implicit


objects −

S.No Implicit object & Description

pageScope
1
Scoped variables from page scope

requestScope
2
Scoped variables from request scope

sessionScope
3
Scoped variables from session scope

applicationScope
4
Scoped variables from application scope

param
5
Request parameters as strings

paramValues
6
Request parameters as collections of strings

header
7
HTTP request headers as strings

headerValues
8
HTTP request headers as collections of strings
initParam
9
Context-initialization parameters

cookie
10
Cookie values

pageContext
11
The JSP PageContext object for the current page

JSP Standard Tag Libraries


we will understand the different tags in JSP. The JavaServer Pages
Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates the core functionality common to many JSP
applications.

JSTL has support for common, structural tasks such as iteration


and conditionals, tags for manipulating XML documents,
internationalization tags, and SQL tags. It also provides a
framework for integrating the existing custom tags with the JSTL
tags.

Install JSTL Library

To begin working with JSP tages you need to first install the JSTL
library. If you are using the Apache Tomcat container, then follow
these two steps −

Step 1 − Download the binary distribution from Apache Standard


Tagliband unpack the compressed file.

Step 2 − To use the Standard Taglib from its Jakarta Taglibs


distribution, simply copy the JAR files in the distribution's 'lib'
directory to your application's webapps\ROOT\WEB-INF\
lib directory.

To use any of the libraries, you must include a <taglib> directive


at the top of each JSP that uses the library.

Classification of The JSTL Tags

The JSTL tags can be classified, according to their functions, into


the following JSTL tag library groups that can be used when
creating a JSP page −

 Core Tags
 Formatting tags

 SQL tags

 XML tags

 JSTL Functions

Explore our latest online courses and learn new skills at your own
pace. Enroll and become a certified expert to boost your career.

Core Tags

The core group of tags are the most commonly used JSTL tags.
Following is the syntax to include the JSTL Core library in your JSP

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"


%>

Following table lists out the core JSTL Tags −

S.No. Tag & Description

<c:out>
1
Like <%= ... >, but for expressions.

<c:set >
2
Sets the result of an expression evaluation in a 'scope'

<c:remove >
3 Removes a scoped variable (from a particular scope, if
specified).

<c:catch>
4 Catches any Throwable that occurs in its body and
optionally exposes it.

5 <c:if>
Simple conditional tag which evalutes its body if the
supplied condition is true.

<c:choose>

6 Simple conditional tag that establishes a context for


mutually exclusive conditional operations, marked
by <when> and <otherwise>.

<c:when>
7 Subtag of <choose> that includes its body if its
condition evalutes to 'true'.

<c:otherwise >

8 Subtag of <choose> that follows the <when> tags and


runs only if all of the prior conditions evaluated
to 'false'.

<c:import>

9 Retrieves an absolute or relative URL and exposes its


contents to either the page, a String in 'var', or a
Reader in 'varReader'.

<c:forEach >

10 The basic iteration tag, accepting many different


collection types and supporting subsetting and other
functionality .

<c:forTokens>
11 Iterates over tokens, separated by the supplied
delimeters.

<c:param>
12
Adds a parameter to a containing 'import' tag's URL.

<c:redirect >
13
Redirects to a new URL.
<c:url>
14
Creates a URL with optional query parameters

Formatting Tags

The JSTL formatting tags are used to format and display text, the
date, the time, and numbers for internationalized Websites.
Following is the syntax to include Formatting library in your JSP −

<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt"


%>

Following table lists out the Formatting JSTL Tags −

S.No. Tag & Description

<fmt:formatNumber>
1 To render numerical value with specific precision or
format.

<fmt:parseNumber>
2 Parses the string representation of a number, currency,
or percentage.

<fmt:formatDate>
3 Formats a date and/or time using the supplied styles
and pattern.

<fmt:parseDate>
4
Parses the string representation of a date and/or time

<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.

<fmt:setLocale>
6 Stores the given locale in the locale configuration
variable.
<fmt:setBundle>
7 Loads a resource bundle and stores it in the named
scoped variable or the bundle configuration variable.

<fmt:timeZone>
8 Specifies the time zone for any time formatting or
parsing actions nested in its body.

<fmt:setTimeZone>
9 Stores the given time zone in the time zone
configuration variable

<fmt:message>
10
Displays an internationalized message.

<fmt:requestEncoding>
11
Sets the request character encoding

SQL Tags

The JSTL SQL tag library provides tags for interacting with
relational databases (RDBMSs) such as Oracle, mySQL,
or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP −

<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql"


%>

Following table lists out the SQL JSTL Tags −

S.No. Tag & Description

<sql:setDataSource>
1 Creates a simple DataSource suitable only for
prototyping

2 <sql:query>

Executes the SQL query defined in its body or through


the sql attribute.

<sql:update>
3 Executes the SQL update defined in its body or through
the sql attribute.

<sql:param>
4 Sets a parameter in an SQL statement to the specified
value.

<sql:dateParam>
5 Sets a parameter in an SQL statement to the specified
java.util.Date value.

<sql:transaction >

6 Provides nested database action elements with a


shared Connection, set up to execute all statements as
one transaction.

XML tags

The JSTL XML tags provide a JSP-centric way of creating and


manipulating the XML documents. Following is the syntax to
include the JSTL XML library in your JSP.

The JSTL XML tag library has custom tags for interacting with the
XML data. This includes parsing the XML, transforming the XML
data, and the flow control based on the XPath expressions.

<%@ taglib prefix = "x"

uri = "http://java.sun.com/jsp/jstl/xml" %>

Before you proceed with the examples, you will need to copy the
following two XML and XPath related libraries into your <Tomcat
Installation Directory>\lib −

 XercesImpl.jar − Download it
from https://www.apache.org/dist/xerces/j/

 xalan.jar − Download it
from https://xml.apache.org/xalan-j/index.html
Following is the list of XML JSTL Tags −

S.No. Tag & Description

<x:out>
1
Like <%= ... >, but for XPath expressions.

<x:parse>
2 Used to parse the XML data specified either via an
attribute or in the tag body.

<x:set >
3
Sets a variable to the value of an XPath expression.

<x:if >

4 Evaluates a test XPath expression and if it is true, it


processes its body. If the test condition is false, the
body is ignored.

<x:forEach>
5
To loop over nodes in an XML document.

<x:choose>

6 Simple conditional tag that establishes a context for


mutually exclusive conditional operations, marked
by <when> and <otherwise> tags.

<x:when >
7 Subtag of <choose> that includes its body if its
expression evalutes to 'true'.

<x:otherwise >

8 Subtag of <choose> that follows the <when> tags and


runs only if all of the prior conditions evaluates to
'false'.

9 <x:transform >
Applies an XSL transformation on a XML document

<x:param >
10 Used along with the transform tag to set a parameter
in the XSLT stylesheet

JSTL Functions

JSTL includes a number of standard functions, most of which are


common string manipulation functions. Following is the syntax to
include JSTL Functions library in your JSP −

<%@ taglib prefix = "fn"

uri = "http://java.sun.com/jsp/jstl/functions" %>

Following table lists out the various JSTL Functions −

S.No. Function & Description

fn:contains()
1
Tests if an input string contains the specified substring.

fn:containsIgnoreCase()
2 Tests if an input string contains the specified substring
in a case insensitive way.

fn:endsWith()
3
Tests if an input string ends with the specified suffix.

fn:escapeXml()
4 Escapes characters that can be interpreted as XML
markup.

fn:indexOf()
5 Returns the index withing a string of the first
occurrence of a specified substring.
fn:join()
6
Joins all elements of an array into a string.

fn:length()
7 Returns the number of items in a collection, or the
number of characters in a string.

fn:replace()
8 Returns a string resulting from replacing in an input
string all occurrences with a given string.

fn:split()
9
Splits a string into an array of substrings.

fn:startsWith()
10
Tests if an input string starts with the specified prefix.

fn:substring()
11
Returns a subset of a string.

fn:substringAfter()
12 Returns a subset of a string following a specific
substring.

fn:substringBefore()
13
Returns a subset of a string before a specific substring.

fn:toLowerCase()
14
Converts all of the characters of a string to lower case.

fn:toUpperCase()
15
Converts all of the characters of a string to upper case.

16 fn:trim()
Removes white spaces from both ends of a string.

JSP Custom Tag


we will discuss the Custom Tags in JSP. A custom tag is a user-
defined JSP language element. When a JSP page containing a
custom tag is translated into a servlet, the tag is converted to
operations on an object called a tag handler. The Web container
then invokes those operations when the JSP page's servlet is
executed.

JSP tag extensions lets you create new tags that you can insert
directly into a JavaServer Page. The JSP 2.0 specification
introduced the Simple Tag Handlers for writing these custom
tags.

To write a custom tag, you can simply


extend SimpleTagSupport class and override the doTag() method,
where you can place your code to generate content for the tag.

Create "Hello" Tag

Consider you want to define a custom tag named <ex:Hello> and


you want to use it in the following fashion without a body −

<ex:Hello />

To create a custom JSP tag, you must first create a Java class that
acts as a tag handler. Let us now create the HelloTag class as
follows −

package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;

public class HelloTag extends SimpleTagSupport {

public void doTag() throws JspException, IOException {

JspWriter out = getJspContext().getOut();

out.println("Hello Custom Tag!");

}
}

The above code has simple coding where the doTag() method
takes the current JspContext object using
the getJspContext() method and uses it to send "Hello Custom
Tag!" to the current JspWriter object

Let us compile the above class and copy it in a directory available


in the environment variable CLASSPATH. Finally, create the
following tag library file: <Tomcat-Installation-
Directory>webapps\ROOT\WEB-INF\custom.tld.

<taglib>

<tlib-version>1.0</tlib-version>

<jsp-version>2.0</jsp-version>

<short-name>Example TLD</short-name>

<tag>

<name>Hello</name>

<tag-class>com.tutorialspoint.HelloTag</tag-class>

<body-content>empty</body-content>

</tag>

</taglib>

Let us now use the above defined custom tag Hello in our JSP
program as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>

<head>

<title>A sample custom tag</title>

</head>

<body>

<ex:Hello/>
</body>

</html>

Call the above JSP and this should produce the following result −

Hello Custom Tag!

Accessing the Tag Body

You can include a message in the body of the tag as you have
seen with standard tags. Consider you want to define a custom
tag named <ex:Hello> and you want to use it in the following
fashion with a body −

<ex:Hello>

This is message body

</ex:Hello>

Let us make the following changes in the above tag code to


process the body of the tag −

package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;

public class HelloTag extends SimpleTagSupport {

StringWriter sw = new StringWriter();

public void doTag()

throws JspException, IOException {

getJspBody().invoke(sw);

getJspContext().getOut().println(sw.toString());

}
Here, the output resulting from the invocation is first captured
into a StringWriter before being written to the JspWriter
associated with the tag. We need to change TLD file as follows −

<taglib>

<tlib-version>1.0</tlib-version>

<jsp-version>2.0</jsp-version>

<short-name>Example TLD with Body</short-name>

<tag>

<name>Hello</name>

<tag-class>com.tutorialspoint.HelloTag</tag-class>

<body-content>scriptless</body-content>

</tag>

</taglib>

Let us now call the above tag with proper body as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>

<head>

<title>A sample custom tag</title>

</head>

<body>

<ex:Hello>

This is message body

</ex:Hello>

</body>

</html>

You will receive the following result −

This is message body


Explore our latest online courses and learn new skills at your own
pace. Enroll and become a certified expert to boost your career.

Custom Tag Attributes

You can use various attributes along with your custom tags. To
accept an attribute value, a custom tag class needs to implement
the settermethods, identical to the JavaBean setter methods as
shown below −

package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;

public class HelloTag extends SimpleTagSupport {

private String message;

public void setMessage(String msg) {

this.message = msg;

StringWriter sw = new StringWriter();

public void doTag()

throws JspException, IOException {

if (message != null) {

/* Use message from attribute */

JspWriter out = getJspContext().getOut();

out.println( message );

} else {
/* use message from the body */

getJspBody().invoke(sw);

getJspContext().getOut().println(sw.toString());

The attribute's name is "message", so the setter method


is setMessage(). Let us now add this attribute in the TLD file
using the <attribute> element as follows −

<taglib>

<tlib-version>1.0</tlib-version>

<jsp-version>2.0</jsp-version>

<short-name>Example TLD with Body</short-name>

<tag>

<name>Hello</name>

<tag-class>com.tutorialspoint.HelloTag</tag-class>

<body-content>scriptless</body-content>

<attribute>

<name>message</name>

</attribute>

</tag>

</taglib>

Let us follow JSP with message attribute as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>

<head>
<title>A sample custom tag</title>

</head>

<body>

<ex:Hello message = "This is custom tag" />

</body>

</html>

This will produce following result −

This is custom tag

Consider including the following properties for an attribute −

S.No. Property & Purpose

name

1 The name element defines the name of an attribute.


Each attribute name must be unique for a particular
tag.

required
2 This specifies if this attribute is required or is an
optional one. It would be false for optional.

rtexprvalue
3 Declares if a runtime expression value for a tag
attribute is valid

type
4 Defines the Java class-type of this attribute. By default
it is assumed as String

description
5
Informational description can be provided.

6 fragment
Declares if this attribute value should be treated as
a JspFragment.

Following is the example to specify properties related to an


attribute −

.....

<attribute>

<name>attribute_name</name>

<required>false</required>

<type>java.util.Date</type>

<fragment>false</fragment>

</attribute>

.....

If you are using two attributes, then you can modify your TLD as
follows −

.....

<attribute>

<name>attribute_name1</name>

<required>false</required>

<type>java.util.Boolean</type>

<fragment>false</fragment>

</attribute>

<attribute>

<name>attribute_name2</name>

<required>true</required>

<type>java.util.Date</type>

</attribute>

.....

JSP Session Management


we will discuss session tracking in JSP. HTTP is a "stateless"
protocol which means each time a client retrieves a Webpage, the
client opens a separate connection to the Web server and the
server automatically does not keep any record of previous client
request.

Maintaining Session Between Web Client And Server

Let us now discuss a few options to maintain the session between


the Web Client and the Web Server −

Cookies

A webserver can assign a unique session ID as a cookie to each


web client and for subsequent requests from the client they can
be recognized using the received cookie.

This may not be an effective way as the browser at times does not
support a cookie. It is not recommended to use this procedure to
maintain the sessions.

Hidden Form Fields

A web server can send a hidden HTML form field along with a
unique session ID as follows −

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified
name and value are automatically included in the GET or
the POST data. Each time the web browser sends the request
back, the session_id value can be used to keep the track of
different web browsers.

This can be an effective way of keeping track of the session but


clicking on a regular (<A HREF...>) hypertext link does not result
in a form submission, so hidden form fields also cannot support
general session tracking.

URL Rewriting

You can append some extra data at the end of each URL. This
data identifies the session; the server can associate that session
identifier with the data it has stored about that session.

For example,
with http://tutorialspoint.com/file.htm;sessionid=12345, the
session identifier is attached as sessionid = 12345 which can be
accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for
the browsers when they don't support cookies. The drawback
here is that you will have to generate every URL dynamically to
assign a session ID though page is a simple static HTML page.

The session Object

Apart from the above mentioned options, JSP makes use of the
servlet provided HttpSession Interface. This interface provides a
way to identify a user across.

 a one page request or

 visit to a website or

 store information about that user

By default, JSPs have session tracking enabled and a new


HttpSession object is instantiated for each new client
automatically. Disabling session tracking requires explicitly
turning it off by setting the page directive session attribute to
false as follows −

<%@ page session = "false" %>

The JSP engine exposes the HttpSession object to the JSP author
through the implicit session object. Since session object is
already provided to the JSP programmer, the programmer can
immediately begin storing and retrieving data from the object
without any initialization or getSession().

Here is a summary of important methods available through the


session object −

S.No. Method & Description

public Object getAttribute(String name)

1 This method returns the object bound with the


specified name in this session, or null if no object is
bound under the name.

2 public Enumeration getAttributeNames()

This method returns an Enumeration of String objects


containing the names of all the objects bound to this
session.

public long getCreationTime()

3 This method returns the time when this session was


created, measured in milliseconds since midnight
January 1, 1970 GMT.

public String getId()


4 This method returns a string containing the unique
identifier assigned to this session.

public long getLastAccessedTime()

5 This method returns the last time the client sent a


request associated with the this session, as the number
of milliseconds since midnight January 1, 1970 GMT.

public int getMaxInactiveInterval()

6 This method returns the maximum time interval, in


seconds, that the servlet container will keep this
session open between client accesses.

public void invalidate()


7 This method invalidates this session and unbinds any
objects bound to it.

public boolean isNew()

8 This method returns true if the client does not yet


know about the session or if the client chooses not to
join the session.

public void removeAttribute(String name)


9 This method removes the object bound with the
specified name from this session.

10 public void setAttribute(String name, Object value)

This method binds an object to this session, using the


name specified.

public void setMaxInactiveInterval(int interval)

11 This method specifies the time, in seconds, between


client requests before the servlet container will
invalidate this session.

Session Tracking Example

This example describes how to use the HttpSession object to find


out the creation time and the last-accessed time for a session. We
would associate a new session with the request if one does not
already exist.

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

<%

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.

Date lastAccessTime = new


Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your Webpage.

if (session.isNew() ){

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

session.setAttribute(visitCountKey, visitCount);
}

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

%>

<html>

<head>

<title>Session Tracking</title>

</head>

<body>

<center>

<h1>Session Tracking</h1>

</center>

<table border = "1" align = "center">

<tr bgcolor = "#949494">

<th>Session info</th>

<th>Value</th>

</tr>

<tr>

<td>id</td>

<td><% out.print( session.getId()); %></td>

</tr>

<tr>

<td>Creation Time</td>

<td><% out.print(createTime); %></td>


</tr>

<tr>

<td>Time of Last Access</td>

<td><% out.print(lastAccessTime); %></td>

</tr>

<tr>

<td>User ID</td>

<td><% out.print(userID); %></td>

</tr>

<tr>

<td>Number of visits</td>

<td><% out.print(visitCount); %></td>

</tr>

</table>

</body>

</html>

Now put the above code in main.jsp and try to


access http://localhost:8080/main.jsp. Once you run the URL, you
will receive the following result −

Welcome to my website

Session Information

Session info value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD
Number of visits 0

Now try to run the same JSP for the second time, you will receive
the following result.

Welcome Back to my website

Session Information

info type value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 1

Deleting Session Data

When you are done with a user's session data, you have several
options −

 Remove a particular attribute − You can call the public void


removeAttribute(String name) method to delete the value
associated with the a particular key.

 Delete the whole session − You can call the public void
invalidate() method to discard an entire session.

 Setting Session timeout − You can call the public void


setMaxInactiveInterval(int interval) method to set the
timeout for a session individually.

 Log the user out − The servers that support servlets 2.4,
you can call logout to log the client out of the Web server
and invalidate all sessions belonging to all the users.
 web.xml Configuration − If you are using Tomcat, apart from
the above mentioned methods, you can configure the
session time out in web.xml file as follows.

<session-config>

<session-timeout>15</session-timeout>

</session-config>

The timeout is expressed as minutes, and overrides the default


timeout which is 30 minutes in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the


timeout period for that session in seconds. So if your session is
configured in web.xml for 15
minutes, getMaxInactiveInterval( )returns 900.

You might also like