ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Java Server Pages (JSP)

Java Server Pages (JSP) is a Java API in J2EE which allows dynamic creation of web pages using Java. It has the same purpose as other existing technologies like CGI or PHP. A JSP page is a text-based document that contains two types of text:

Static template data: which can be expressed in any text-based format, such as HTML,SVG, WML, and XML and will be used for presentation.

JSP elements: which construct dynamic content based on the logic.

JSP provides clear separation between logic and presentation. JSP simply puts Java code inside HTML pages and saving the file with .jsp extension.

Disadvantages with Servlets: When we are developing servlets, we need to have many things in to consideration like overriding service methods and entries in web.xml. From the developer’s perspective, Servlets are pure java programs with class and method definitions whereas a JSP page is much like a text document or web page. With servlets, developer must write java code to output the entire markup, on the other hand a JSP page can be designed like a static web page. Servlets are well suited for handling client request and executing application logic whereas JSP pages are well suited as views and application logics also. It's hard to take advantage of web-page development tools when designing the application interface. If such tools are used to develop the web page layout, the generated HTML must embedded into the servlet code manually, which is time consuming, error prone, and extremely boring.

Benefits of JSP: JSP allows the Separation of request processing, business logic, and presentation. Auto transition and compilation. Means we need not recompile every time when we do changes in JSP. There is no deployment descriptor for JSP. Multiple deployment is avoided. Means on the fly we can do changes to JSP Pages. JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA servlets. JSP uses simplified scripting language based syntax for embedding HTML into JSP. JSP containers provide easy way for accessing standard objects and actions. JSP use HTTP as default request /response communication paradigm and thus make JSP ideal as Web Enabling Technology.

1 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

JSP Application Processing A JSP page cannot be sent as-is to the browser; all JSP elements must first be processed by the server. This is done by turning the JSP page into a servlet, and then executing the servlet. A JSP container is responsible for converting the JSP page into a servlet. The lifecycle of a JSP is as follows

2 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Life cycle of a JSP page consists of three phases. Those are Translation phase Compilation phase Execution phase

Translation Phase Here the web container will translates the .jsp page into a servlet compatible java file. Here the entire static markup in the JSP page is converted into the code that writes the data to response stream.

During the translation phase JSP elements are treated as follows:

JSP directives control the behavior of the resultant servlet. Scripting elements results into the equivalent Java code. Custom tags are converted into the code that calls method on tag handlers

Compilation Phase Here servlet compatible java file will be compiled into a class file.

Execution Phase Executes the servlet (response is sent to the client). JSP life cycle's execution phase is almost similar to that of the Servlet life cycle, because ultimately it's a servlet which is being executed. The Servlet class generated at the end of the translation phase represents the contract between container and the JSP page.

JSP life cycle includes three methods jspInit(), _jspService() and jspDestroy() jspInit(): This method is invoked when the JSP page is initialized. This method is similar to init() method in servlet. If we want to provide initialization for a JSP page, we define this method in declaration part of the JSP page.

_jspService( ): This method represents the body of the JSP page and invoked at each client request. This method is similar to service() method in servlet. jspDestroy(): This method is called only once in JSP's servlet life time, when the JSP Engine removes the JSP's servlet from memory. It is always better to remove instance variable resources such as JDBC connections, sockets.

3 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Anatomy/Structure of a JSP Page A JSP page is a mixture of standard HTML tags, web page content, and some dynamic content that is specified using JSP Elements and implicit objects. Everything except the JSP constructs is called Template Text which can be text or HTML. Template text can be any text: HTML, WML, XML, or even plain text.

JSP Elements (Tags)

There are six types of JSP elements that we can use and they are:

1. Declaration Element 2. Scriptlets 3. Expression Element 4. Comments 5. Elements 6. Action Elements

Scriptlet:

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Following is the syntax of Scriptlet:

<% code fragment %>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

4 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Hello World

Hello World!
<% out.println("Welcome to JSP”); %>

JSP Declarations:

A declaration declares one or more variables or methods that we can use in Java code later in the JSP file. We must declare the variable or method before we use it in the JSP file.

Following is the syntax of JSP Declarations:

<%! declaration; [ declaration; ]+ ... %>

Following is the simple example for JSP Declarations:

<%! int i = 0; %> <%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %> <%! public void jspInit() {

}%

JSP Expression:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, we can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but we cannot use a semicolon to end an expression. Following is the

5 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT syntax of JSP Expression:

<%= expression %>

Example:

Todays Date: <% = new java.util.Date() %> Which would generate the following output Todays Date: 07-July-2011 14:45:55

JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the following form:

<%@ directive attribute="value" %>

There are three types of directive tag:

Directive Description Defines page-dependent attributes, such as scripting language, error <%@ page ... %> page, and buffering requirements <%@ include ... %> Includes a file during the translation phase. <%@ taglib ... %> Declares a tag , containing custom actions, used in the page

Page Directive: The page directive is used to provide instructions to the container that pertain to the current JSP page. We may code page directives anywhere in our JSP page. By convention, page directives are coded at the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value"

Include Directive: The include directive is used to includes 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 include directives anywhere in your JSP page.

The general usage form of this directive is as follows:

6 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

<%@ include file="relative url" >

Example:

A good example of include directive is including a common header and footer with multiple pages of content. Let us define following three files (a) header.jps (b)footer.jsp and ()main.jsp as follows:

Following is the content of header.jsp: <%!

int pageCount = ; void addCount() { pageCount++; } %>

<% addCount(); %>

The include Directive Example

The include Directive Example

This site has been visited <%= pageCount %> times.



Following is the content of footer.jsp:



Copyright © 2010

Finally here is the content of main.jsp:

7 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

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

Thanks for visiting my page.

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

Now let us keep all these files in root directory and try to access main.jsp. This would display follow result:

This site has been visited 1 times.

Thanks for visiting my page.

Copyright © 2010

Taglib Directive:

The JavaServer Pages API allows us 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 our JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in our JSP page. The taglib directive follows the following syntax:

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

Where 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.

8 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

JSP Implicit Objects

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.JSP supports nine Implicit Objects which are listed below: JSP object Servlet API Object Description Scope request javax.servlet.HttpServletRequest The client request. Request session javax.servlet.http.HttpSession Session object created Session for requesting client. application javax.servlet.ServletContext Context (Execution Application environment) of the Servlet. config javax.servlet.ServletConfig The ServletConfig for Page the JSP. exception java.lang.Throwable The exception that Page resulted when an error occurred. pageContext javax.servlet.jsp.PageContext Page context for the Page JSP. response javax.servlet.HttpServletResponse The response to the Page client. page javax.servlet.Servlet Refers to current Page servlet object. out javax.servlet.jsp.JspWriter An object that writes Page into a JSP's output stream.

9 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT 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 HTTP header information including form data, cookies, HTTP methods etc. Cookie[] getCookies() HttpSession getSession() int getIntHeader(java.lang.String name) String getHeader(String name) String getServletPath() String getMethod() String getContextPath() 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. void addCookie(Cookie cookie) void addHeader( String name, String value) void setHeader( String name, String value) void setIntHeader( String name, int value) void sendRedirect( String location) out Object:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object 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. The JspWriter object contains most of the same methods as the java.io.PrintWriter class. Unlike the PrintWriter object, JspWriter throws IOExceptions. Following are the important methods which we would use to write boolean char, int, double, object, String etc.

Method Description out.print(dataType dt) Print a value out.println(dataType dt) Print a data type value then terminate the line with new line.

10 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT session Object:

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets. The session object is used to track client session between client requests.

Object getAttribute( String name) void setAttribute( String name, Object value) Enumeration getAttributeNames() void removeAttribute( String name) void putValue( String name, Object value) Object getValue( String name) String[] getValueNames() void removeValue( String name) String getId() long getCreationTime() long getLastAccessedTime() int getMaxInactiveInterval() void setMaxInactiveInterval(int interval) void invalidate() boolean isNew()

application Object:

The application object is direct wrapper around the ServletContext object 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, we can ensure that all JSP files that make up our web application have access to it. Object getAttribute(String name) Enumeration getAttributeNames() void removeAttribute( String name) void setAttribute(java.lang.String name, Object object) Servlet getServlet(java.lang.String name) Enumeration getServletNames() void log( String msg)

11 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT config Object:

The config object is an instantiation of javax.servlet.ServletConfig and 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:

String getInitParameter(String name) Enumeration getInitParameterNames() String getServletName() ServletContext getServletConext()

This returns the servlet name, which is the string contained in the element 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. 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 this object.

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. The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages.

String getMessage() String printStackTrace() String toString()

12 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

JSP Actions

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. We 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:

Action elements are basically predefined functions and there are following JSP actions available:

Syntax Purpose jsp:include Includes a file at the time the page is requested jsp:useBean Finds or instantiates a JavaBean jsp:setProperty Sets the property of a JavaBean jsp:getProperty Inserts the property of a JavaBean into the output jsp:forward Forwards the requester to a new page Generates browser-specific code that makes an OBJECT or jsp:plugin EMBED tag for the Java plugin

Action

This action allows us to insert files into the page being generated. The syntax looks like this:

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 is the list of attributes associated with include action:

Attribute Description page The relative URL of the page to be included. The boolean attribute determines whether the included flush resource has its buffer flushed before it is included.

13 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Example:

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

Following is the content of date.jsp file:

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

Here is the content of main.jsp file:

The include Action Example

The include action Example

Now let us keep all these files in root directory and try to access main.jsp. This would display result something like this:

The include action Example Today's date: 12-Sep-2010 14:54:22

14 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

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:

Once a bean class is loaded, we can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.

Following is the list of attributes associated with useBean action:

Attribute Description class Designates the full package name of the bean. Specifies the type of the variable that will refer to the type object. Gives the name of the bean as specified by the instantiate beanName ()method of the java.beans.Beans class.

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:

We can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

...

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 below:

15 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

...

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

Following is the list of attributes associated with setProperty action:

Attribute Description name Designates the bean whose property will be set. The Bean must have been previously defined. property Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. value 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 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.

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 ans simple syntax is as follows:

...

16 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Following is the list of required attributes associated with getProperty action:

Attribute Description name The name of the Bean that has a property to be retrieved. The Bean must have been previously defined. property The property attribute is the name of the Bean property to be retrieved.

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.

The simple syntax of this action is as follows:

Following is the list of required attributes associated with forward action:

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

Let us reuse following two files (a) date.jps and (b) main.jsp as follows: Following is the content of date.jsp file:

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

Here is the content of main.jsp file:

The include Action Example

17 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

The include action Example

Action

The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the or 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 element can also be used to send parameters to the Applet or Bean

Following is the typical syntax of using plugin action:

Unable to initialize Java Plugin

18 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

JSP Error Handling and Debugging

JSP gives us an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page.

To set up an error page, use the

<%@ page errorPage="xxx" %> directive.

Following is an example to specifiy an error page for a main.jsp.

<%@ page errorPage="ShowError.jsp" %>

Error Handling Example

<%

// Throw an exception to invoke the error page int x = 1;

if (x == 1)

{

throw new RuntimeException("Error condition!!!");

}

%>

Now we would have to write one Error Handling JSP ShowError.jsp, which is given below. The error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP to generate the exception instance variable.

19 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

<%@ page isErrorPage="true" %>

Show Error Page

Opps...

Sorry, an error occurred.

Here is the exception stack trace:

 

<% exception.printStackTrace(response.getWriter()); %>

Passing Control and Data between Pages

One of the most fundamental features of JSP technology is that it allows for separation of request processing, business logic and presentation. As part of the MVC, JSP pages are used for both the Controller and View roles, and the Model role is played by either a bean or a JSP page.

For example

20 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Using different JSP pages as Controller and View means that more than one page is used to process a request. To make this happen, you need to be able to do two things: Pass control from one page to another Pass data from one page to another

Passing Control from One Page to Another The control can be passed from one JSP page to another JSP page by using action element. The syntax for is as follows

This action element also has some attributes like

The action stops processing of one page and starts processing the page specified by the page attribute instead, called the target page. The control never returns to the original page. The target page has access to all information about the request, including all request parameters. We can also add additional request parameters when we pass control to another page by using one or more nested action elements

For example

21 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Parameters specified with elements are added to the parameters received with the original request. The target page, therefore, has access to both the original parameters and the new ones, and can access both types in the same way.

Passing Data from One Page to Another JSP provides different scopes for sharing data objects between pages, requests, and users. The scope defines how long the object is available and whether it's available only to one user or to all application users. The following scopes are defined: page, request, session, and application.

Objects placed in the default scope, the page scope, are available only within that page. The request scope is for objects that need to be available to all pages processing the same request. Objects in the session scope are available to all requests made from the same browser. Objects in the application scope are shared by all users of the application

22 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Session Tracking (Sharing Session Data):

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

session Object:

JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically.

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 that object.

Here is a summary of important methods available through session object:

S.N. 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. public Enumeration getAttributeNames() 2 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 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

23 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

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. public void setAttribute(String name, Object value) 10 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:

<%@ page import="java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. 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 web page. 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); %> Session Tracking

Session Tracking

24 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Session info Value
id <% out.print( session.getId()); %>
Creation Time <% out.print(createTime); %>
Time of Last Access <% out.print(lastAccessTime); %>
User ID <% out.print(userID); %>
Number of visits <% out.print(visitCount); %>

Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would display the following result when you would run for the first time:

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

25 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Now try to run the same JSP for second time, it would display following result. 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 we are done with a user's session data, we have several options:

Remove a particular attribute: We can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session: We can call public void invalidate() method to discard an entire session. Setting Session timeout: We can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. web.xml Configuration: If we are using Tomcat, we can configure session time out in web.xml file as follows.

15

Memory Usage Considerations

We should be aware that all objects you save in the application and session scopes take up memory in the server process. It's easy to calculate how much memory is used for the application scope because we have full control over the number of objects we placed there. But the total number of objects in the session scope depends on the number of concurrent sessions, so in addition to the size of each object, you also need to know how many concurrent users you have and how long a session lasts Here are some things we can do to keep the memory requirements under control:

26 DEPARTMENT OF INFORMATION TECHNOLOGY

ADVANCED JAVA PROGRAMMING - UNIT -VI III – II IT

Place only objects that really need to be unique for each session in the session scope. In the shopping cart example, each cart contains only references to the product beans (not copies of the beans), Set the timeout period for sessions to a lower value than the default. Provide a way to end the session explicitly. A good example is a logout function, or invalidation of the session when something is completed

27 DEPARTMENT OF INFORMATION TECHNOLOGY