+ All Categories
Home > Education > The java enterprise edition (Servlet Basic)

The java enterprise edition (Servlet Basic)

Date post: 11-May-2015
Category:
Upload: atul-saurabh
View: 451 times
Download: 1 times
Share this document with a friend
67
A robust and Scalable way t o design Large Scale Distributed Application THE JA VA ENTERPRISE EDITIO N
Transcript
Page 1: The java enterprise edition (Servlet Basic)

A robust a

nd Scalable way to

design Large Scale Distributed

Applicatio

n

THE JAVA ENTERPRISE EDITION

Page 2: The java enterprise edition (Servlet Basic)

• In a broad term, an enterprise means a business organization. The functionality of the organization may limited to one single unit or may be distributed over multiple units and possibly units are situated at geographically different location. Also different unit follows different policies and rules. To manage these diversities with automation requires lot of effort. One single bug can harm the organization.

Enterprise

Page 3: The java enterprise edition (Servlet Basic)

• Each business organization has its own set of rules and policies

• Organization may have different set of activities

• An enterprise programming facilitate various activities in an enterprise by following rules and policies.

• In another word, enterprise application are one which helps an enterprise to manage its various activities.

Enterprise programming

Page 4: The java enterprise edition (Servlet Basic)

• A well designed E-app must meet the following goals:

• Robustness : - Should have no or less number of bugs.

• Scalability and Performance :- Scalability refers to the term that the potential for an application to support increased load, given the appropriate hardware. The E-app must be designed in such a manner that it should not degrade its performance if load increases suddenly.

• Maintainable & extensible : - A well designed E-app should be easy maintainable. If bugs are reported the it should be removed easily.

Also new features can be added easily.

GOALS of well d

esigned E-APPS

Page 5: The java enterprise edition (Servlet Basic)

Followings are the advantage of JAVA in E-programming

• Platform Independent : - Wide ranging scattered enterprise information that too in disparate formats are available that may be spread across different platform. So we need to adopt a programming language which function evenly well throughout the enterprise.

• Managed Object :- JEE application are container centric. Due to this property, JEE component utilize the infrastructure provided by the JEE server without the programmer being aware of it.

• Reusability : - Java is OO language. Objects can be reused in many different ways to achieve different functionalities.

• Modularity :-

Advantage of JAVA in

E-programming

Page 6: The java enterprise edition (Servlet Basic)

A software application composition can be broken down into three fundamental concerns or logical layers.

• The UI : - This is responsible for displaying stuff to the user and collecting data from the user. Also called Presentation Layer.

• Processing:- In this layer, the application works and handles the important processing. This logical layer is called Business rule layer.

• Data Storage land Access : - All non-trivial business applications need to read and store the data. The part of the software that is responsible for writing data to the source and reading it from the source is called Data Access Layer.

On the basis of deployment of these three layers, the E-app can have the following architecture

Archite

cture of E

-App

Page 7: The java enterprise edition (Servlet Basic)

THE SINGLE TIER ARCHITECTURE

The UI

The Business Rule

Data Access

Page 8: The java enterprise edition (Servlet Basic)

• All the concerns are deployed on a single machine.

• Strictly for single user

• Easy to develop and maintain.

Multiple user support is not available

Hard to share data across enterprise.

Pros and co

ns of s

ingle tier

Page 9: The java enterprise edition (Servlet Basic)

The 2 tier architecture

The UI

The Business Layer

Data Access

Request

Page 10: The java enterprise edition (Servlet Basic)

• Data can be shared between multiple users.

• Multi-user system

The centralized database system may be the bottleneck.

The client side resource consumption is very high and so the client is called FAT client.

Pros and co

ns of 2

tier

Page 11: The java enterprise edition (Servlet Basic)

The UI

Data Access

The 3 tier architecture

Request

ResponseThe Business Layer

Request

Response

Page 12: The java enterprise edition (Servlet Basic)

• Data can be shared between multiple users.

• Multi-user system

• Less number of resource is consumed on client side and hence client is called THIN client.

• Easy for maintenance.

• Extendable

There is no clear separation between presentation and logic. So hard to develop.

Pros and co

ns of 3

tier

Page 13: The java enterprise edition (Servlet Basic)

J2EE archite

cture

C1

C2

C3

Web Container

EJB container

EIS

Page 14: The java enterprise edition (Servlet Basic)

In JEE app, containers are the central theme. A container provides the runtime environment for various component of JEE apps. It acts as a runtime interface between the application components and the low level platform specific functionalities. The JEE containers provides development, management and execution support for application components.

Containers

Page 15: The java enterprise edition (Servlet Basic)

There are four types of container

1. EJB Container : It manages the execution of all the enterprise bean for one JEE application.

2. Web Container : A web container manages the execution of all JSP pages and servlet for one JEE application.

3. Application Client Container : It manages the execution of all application client component for one JEE application.

4. Applet Container : It is a combination of web browser and java plug-in running together on the client machine. Types o

f Container

Page 16: The java enterprise edition (Servlet Basic)

HTTP is also known as Hyper-Text Transfer Protocol. It is an application level protocol. It is the mode by which web pages are communicated across the internet.

Normally this protocol is used in communication between client and the server. Here are the steps followed in this protocol:

HTTPClient Server

1. Connect

2. Request

3. Response

4. Close

Page 17: The java enterprise edition (Servlet Basic)

A HTTP transaction begins with a request from the client’s browser and ends with a response from the server. The HTTP request consists of three components :

1. Method URI Protocol/Version

2. Request Header

3. Entire Body

Example

GET /servlet/default.jsp HTTP/1.1

Accept : text/plain ; text/html

Accept-Language : en-gb

Connection : Keep-Alive

HOST : localhost

User-Agent : Mozilla/4.0(Compatible; MSIE 4.01; windows 98)

Content-Length : 33

LastName=Saurabh&FirstName=Atul

HTTP Request

Page 18: The java enterprise edition (Servlet Basic)

Whenever client need to send some request to the server it uses some HTTP specific method.

HTTP 1.0 defines only two methods GET and POST. HTTP 1.1 defines five more.

HTTP Methods

Method Description

GET GET is the simplest and most used method. GET simply retrieves the data identified by the URI.

HEAD This is similar to GET but it only retrieves the HTTP header and not the body.

Page 19: The java enterprise edition (Servlet Basic)

HTTP Methods c

ont. …

Method Description

POST It is normally used in HTML forms. Post is used to transfer a block of data to the server in the entire body of the request

OPTIONS The OPTIONS method is used to query a server about the capabilities it provides.

PUT It is complementary of GET. It stores the entire body at a location specified by the URI.

Page 20: The java enterprise edition (Servlet Basic)

HTTP Methods c

ont. …

Method Description

DELETE This method is used to delete a document from the server. The document is identified by the URI.

TRACE It is used to trace the path of the request through firewall and multiple proxy server.

Page 21: The java enterprise edition (Servlet Basic)

Similar to HTTP Request , HTTP response consists of three parts:

1. Protocol Status code Description

2. Response Header

3. Entire Body

Example

HTTP/1.1 200 OK

Server : Microsoft IIS/4.0

Date : Mon 3, jan 2007 13:34:60 ISTContent-Type : text/html

Content-Length : 112

<html> <head><title>Example</title></head>

<body>Welcome</body></html>

HTTP Response

Page 22: The java enterprise edition (Servlet Basic)

Role of client, S

erver a

nd Container

Machine Client

Prepare HTTP

Requestport

Request Convert to

object

Process & Prepare response Object

Convert response object

to HTTP response

Cont

aine

r Serv

er

Page 23: The java enterprise edition (Servlet Basic)

A servlet is a java based server side technology runs inside a container called servlet engine.

Servlet interacts with client via a request-response model based on HTTP.

For programming perspective a servlet is defined in two ways:

1. A servlet is a java class embedded with HTML code.

2. A servlet is a java class which extends javax.servlet.http.HttpServlet class.

Servlet D

efinitio

n

Page 24: The java enterprise edition (Servlet Basic)

From the definition it is clear that a servlet is a java class. So,

import javax.servlet.http.HttpServlet;

public class MyServlet extends HttpServlet

{

}

Servlet p

rogrammatically

Page 25: The java enterprise edition (Servlet Basic)

Life Cycl

e of a se

rvlet

Receive Request

Is servlet loaded

Is servlet current

Process request Send Response

Load Servlet

yes

yes

no

no

Page 26: The java enterprise edition (Servlet Basic)

Programmatic life

Cycle of a

servl

et

Receive Request

Is servlet loaded

Is servlet current

Call Service() Send Response

Load Servlet

yes

yes

no

no

Call init()

Call destroy()

No request for long time

Page 27: The java enterprise edition (Servlet Basic)

JEE application requires a certain fixed directory structure so that the server can identify and locate resources in the app. Some names are reserved and must not use elsewhere. Some of the directories are mandatory and some are optional. Here is the structure:

Directo

ry Stru

cture fo

r web app Root(M)

Reserved(M)

Reserved(M)

Reserved(M) Important(M)

Required for specific

purpose(O)

Page 28: The java enterprise edition (Servlet Basic)

1. The Root :- The name of root directory is NOT reserved. It depends upon the project name possibly.

2. WEB-INF : - Its name is reserved and must be located inside the root directory. It is a private directory.

3. WEB-INF/classes : It contains all the java classes.

4. WEB-INF/web.xml : It is called deployment descriptor.

5. WEB-INF/lib : It contains all the external libraries possibly in form of JAR.

6. META-INF : It is optional. But it name is reserved. It contains project related configuration file.

All the JSPs, HTML, JS, CSS etc go inside root directory.

Directo

ry Stru

cture fo

r web app

Page 29: The java enterprise edition (Servlet Basic)

The following are the steps required to run a servlet.

Step -1 : Write a Servlet

Steps for ru

nning a servl

et

import javax.servlet.http.*;import java.io.*;import javax.servlet.*;public class MyServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out=response.getWriter(); out.println(“Hello World!!!”); }}

Page 30: The java enterprise edition (Servlet Basic)

Step -2 : Compile The Servlet

set CLASSPATH=%CATALINA_HOME%\common\lib\servlet.jar;.

javac MyServlet.java

OR

javac classpath %CATALINA_HOME%\common\lib\servlet.jar MyServlet.java

Here CATALINA_HOME represents the installation directory of Apache Tomcat.

Steps for ru

nning a servl

et cont.

Page 31: The java enterprise edition (Servlet Basic)

Step -3 : Create the directory structure for the project. The root folder may have name Test.

Step -4 : Put the servlet class in the WEB-INF\classes directory.

Step -5 : Create the deployment descriptor i.e. web.xml and put the following content in this file….

Steps for ru

nning a servl

et cont.

Page 32: The java enterprise edition (Servlet Basic)

Steps for ru

nning a servl

et cont.

<!DOCTYPE web-app PUBLIC “-//Sun Microsystem,Inc.// DTD Web Application 2.3//EN”http://java.sun.com/dtd/web-app_2_3.dtd><web-app> <servlet> <servlet-name>Sample</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Sample</servlet-name> <url-mapping> /Sample</url-mapping> </servlet-mapping>

</web-app>

Page 33: The java enterprise edition (Servlet Basic)

Step -6 : put the web.xml inside WEB-INF folder.

Step -7 : put the whole directory structure inside %CATALINA_HOME%\web-apps

Step -8 : Run the apache server using %CATALINA_HOME\bin\startup.bat

Step -9: Call the servlet from the browser

http://localhost:8080/Test/SampleSteps for ru

nning a servl

et cont.

Page 34: The java enterprise edition (Servlet Basic)

Here is the class Hierarchy of javax.servlet.http.HttpServlet

Background of S

ervlet

javax.servlet.Servlet

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

implements

extends

Page 35: The java enterprise edition (Servlet Basic)

HttpServlet class gets Life-cycle method from GenericServlet class and GenericServlet provides implementation of all method present inside Servlet interface. Here are the methods defined in Servlet interface

• public void init(ServletConfig config) throws ServletException

• public void service ( ServletRequest request, ServletResponse response) throws IOException, ServletException

• public void destroy()

• public String getServletInfo()

• public ServletConfig getServletConfig()

Background of S

ervlet c

ont.

Page 36: The java enterprise edition (Servlet Basic)

The HttpServlet is basically used to handle HTTP Request.

So HttpServlet defines some of the methods related to HTTP. Here are some of those methods….

1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

2. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

3. protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

Background of S

ervlet c

ont.

Page 37: The java enterprise edition (Servlet Basic)

When a HTTP client sends a request using any HTTP method (GET, POST, DELETE…) then the servlet engine calls corresponding doXXX method. As for example when the client sends a request using DELETE HTTP method then servlet engine call doDelete method. Notice that all doXXX methods are very similar to service method. Here are the steps in handling request using servlet….

1. The server get a request from the client.

2. The server converts the HTTP request into ServertRequest and handed over to the container.

3. The container invoke the servlet mapped by the URI.

4. The container create a thread for each client and the thread calls the service method. The ServletRequest object is handed over to the service method.

5. The service method in turns downcast the ServletRequest into HttpServletRequest and calls the doXXX method.

Background of S

ervlet c

ont.

Page 38: The java enterprise edition (Servlet Basic)

Whenever client need to send some useful information to the server then the message is sent in form of

Key=value

format. As form example

firstname=rahulHere firstname is the key and rahul is the value.

If there are many messages then each one is seperated by &. As for example

firstname=rahul & lastname=duttaThe HttpServletRequest parameter to the doXXX method represents the request sent by the client. This interface provides useful methods to fetch all the parameters sent by the client.

Handling Request

Page 39: The java enterprise edition (Servlet Basic)

Here are the methods provided by the HttpServletRequest interface.

Handling Request

Sl. No Method Signature Description

1. String getParameter(String key) Returns the value associated with the key. Useful when one key is associated with one value only. E.g. fetching the value submitted through the textfield, Dropdown box etc in HTML.

2. String [] getParameterValues(String key)

Returns the array of values associated with the key. Useful when one key is associated with multiple values. E.g. fetching values from HTML checkbox.

Page 40: The java enterprise edition (Servlet Basic)

Handling Request

Sl. No Method Signature Description

3. Enumeration getParameterNames()

Returns all the keys sent by the client. This method can be used in conjunction with getParameter or getParameterValues.

4. RequestDispatcher getRequestDispatcher(String pageName)

Returns RequestDispatcher object to either include the page referred by pageName in the current page or forward to page.

Page 41: The java enterprise edition (Servlet Basic)

Handling Request

Sl. No Method Signature Description

5. String getMethod() Return the HTTP i.e. GET, POST etc. method using that this request is sent.

6. String getRequestURI() Returns the URI associated with this request.

Page 42: The java enterprise edition (Servlet Basic)

Handling Request

Sl. No Method Signature Description

7. String getHeader(String hname) Return the value of the header represented by hname.

8. Enumeration getHeaderNames() Returns the names of all the headers sent by the client

Page 43: The java enterprise edition (Servlet Basic)

Handling Request

Sl. No Method Signature Description

7. InputStream getInputStream() Return the inputstream object if the request contains some binary data.

8. HttpSession getSession()HttpSession getSession(boolean create)

Returns the session object associated with the current request.

Page 44: The java enterprise edition (Servlet Basic)

An Example

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class CheckBoxHandler extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out=response.getWriter(); String choices[] = request.getParameterValues(“myChoice”); out.println(“You have selected…<br>”); for(int i=0; i< choices.length;i++) { out.println(“ “+choices[i]+”<br>”); } }}

2

Page 45: The java enterprise edition (Servlet Basic)

Compile the servlet… Put it at correct place inside the directory structure. Map it inside web.xml and then create an HTML form

An Example Contd.

<body><form method=“POST” actoin=“chkboxhndlr”>

<lable>Cricket</label><input type=“checkbox” value=“cricket” name=“myChoice”/>

<lable>Basket Boll</label><input type=“checkbox” value=“basketboll” name=“myChoice”/>

<lable>Hockey</label><input type=“checkbox” value=“hockey” name=“myChoice”/>

<button type=“submit”>Submit</button></form></body>

3

Page 46: The java enterprise edition (Servlet Basic)

The mapping in web.xml

An Example Contd.

<?xml version="1.0" encoding="UTF-8"?>

<web-app … >

<servlet> <servlet-name>setServlet</servlet-name> <servlet-class> CheckBoxHandler </servlet-class> </servlet>

<servlet-mapping> <servlet-name>setServlet</servlet-name> <url-pattern>/ chkboxhndlr </url-pattern> </servlet-mapping>

</web-app>

1

1

2

3

Page 47: The java enterprise edition (Servlet Basic)

Sometimes it is required to initialize the servlet with some parameters so that when the servlet is up and running the parameters are available to it. This is generally called the configuration of the servlet and is limited to one servlet in context.

The servlet is configured in web.xml i.e. Deployment Descriptor using <init-param> tag. Here is the code snippet :

<servlet>

<servlet-name>abc</servlet-name>

<servlet-class>org.MyServlet</servlet-name>

<init-param>

<param-name>Nname</param-name>

<param-value>Atul</param-value>

</init-param>

</servlet>

The Configuratio

n

A

Page 48: The java enterprise edition (Servlet Basic)

The initialization parameters are available to the servlet via ServletConfig object. The GenericServlet override all the abstract method of Servlet interface. And HttpServlet class extends GenericServlet class. So the ServletConfig object can be obtained using getServletConfig() method. One can use getInitParameter(…) method to obtain the initial configuration values. Here is the code snippet.

The servlet is configured in web.xml i.e. Deployment Descriptor using <init-param> tag. Here is the code snippit :

protected void doGet(…… req, …..res) ….

{

ServletConfig g=getServletConfig();

String nName=g.getInitParameter(“Nname”);

………

}

The Configuratio

n contd.

A

Page 49: The java enterprise edition (Servlet Basic)

Here are the methods defined ServletConfig interface

The Configuratio

n contd.

Sl. No. Method Description

1. String getInitParameter(String key) Returns the values associated with key

2. Enumeration getInitParameterNames()

Returns all the keys defined for the configuration of this servlet

3. ServletContext getServletContext() Returns the context object for this servlet

Page 50: The java enterprise edition (Servlet Basic)

The context represents the run time environment in which the servlet is running. The context is represented by the ServletContext object. Sometimes we need the set the configuration of all servlet running in an environment. That means the configuration is not limited to one particular servlet but available to all. In that case we need to talk to runtime environment and ServletContext will help. The initial configuration is also set in web.xml.

Here is the way:

<web-app>

<context-param>

<param-name>forAll</param-name>

<param-value>Good Morning</param-value>

</context-param>

……

</web-app>

The ContextB

Page 51: The java enterprise edition (Servlet Basic)

Note that the <init-param> is not written inside any <servlet> tag. Here is the way to obtain the initial parameter

protected void doGet(…… req, …….res) ………

{

ServletConfig g=getServletConfig();

ServletContext c=g.getServletContext();

String msg=c.getInitParameter(“forAll”);

………………..

}

The Context contd.

B

Page 52: The java enterprise edition (Servlet Basic)

Here are some of the useful methods defined in ServletContext interface.

The Context contd.

Sl. No Method Description

1. String getInitParameter(String key) Returns the initial parameters associated with the key set for the servlets.

2. Enumeration getInitParameterNames()

Returns keys for all initial parameters set for the servlet.

3. RequestDispatcher getNamedDispatcher(String pageName)

Returns the RequestDispatcher object for moving or including the page identified by pageName

Page 53: The java enterprise edition (Servlet Basic)

The Context contd.

Sl. No Method Description4. void setAttribute(String

attribName,Object attrib)Set the attribute to the session

5. Object getAttribute(String attribName)

Returns the attribute associated with the attribName.

6. RequestDispatcher getRequestDispatcher(String pageName)

Returns the RequestDispatcher object for moving or including the page identified by pageName

Page 54: The java enterprise edition (Servlet Basic)

HTTP is a stateless protocol. That means the server is not going to maintain any state of the client and every request from the client is considered as the fresh request. But in some situation like Book Shopping it is necessary to maintain the state of the client because a client may add some book to its own cart.

The state of client is loosely called its session. More precisely a session is defined as

“A session is an uninterrupted request-response series between a client and the server”.

The uninterrupted does not mean that client need to send the request immediately after it gets the response. Of course there might be a relaxation of time. But the server expect that client must communicate with it within the time limit.

The Session M

anagement

Page 55: The java enterprise edition (Servlet Basic)

Mainly in E-app programmer use two technique to maintain the session.

i) Cookie

ii) HttpSession

The Cookie

The cookie is a small text file in which the server keeps some information related to the client session and store on the client local hard disk. Here are the steps when session is managed by cookie.

1) The server prepare a cookie at some point of time and add it to the response. That means when the client browser get some response it also get the cookie. The browser store the cookie at its local hard disk. Normally the server stores time span, date of creation etc. information in the cookie.

The Session M

anagement

Page 56: The java enterprise edition (Servlet Basic)

Here is piece of code……

protected void doGet(…. Req, …. Res ) …….

{

Cookie c=new Cookie(“MyCookie”,”Add Cart”);

Res.addCookie(c);

}

2) Next time when the browser sends a request to the server, it also sends the cookie to the server. Now it’s the duty of the server to get cookie from the request and perform some analysis task (possibly).

The Cookie

Page 57: The java enterprise edition (Servlet Basic)

protected void doGet(…. Req, …. Res ) …….

{

Cookies [] c=Req.getCookies();

for(int i=0;i<c.length;i++)

{

Cookie c1=c[i];

String value=c1.getValue();

}

}The Cookie

Page 58: The java enterprise edition (Servlet Basic)

Here are some useful method in cookie class.

Useful method of C

ookie

Sl. No Method Description

1. void setMaxAge(int exp) Set age for cookie in seconds

2. void setValue(String value) Set the value in cookie

3. int getMaxAge() Return the life span of the cookie in seconds

4. String getValue() Returns the value set in the cookie.

Page 59: The java enterprise edition (Servlet Basic)

• The cookie is always stored at client side. That is why the resources at server side is saved.

• Cookie is a small textual information which requires less bandwidth to travel back and forth.

• It is always a chance that client may change the data written inside the cookie. So not reliable.

• If the Cookie is deleted, by accident also, the session will be invalidated by the server.Pros a

nd Cons of C

ookie

Page 60: The java enterprise edition (Servlet Basic)

Cookie saves the server resources but gives a strong chance to the client to control the session. This disadvantage make the cookie impractical to maintain cookie.

Java provides one more mechanism to maintain client session. And the mechanism is HttpSession. HttpSession does not allow the client to control the session. The server has full control over the client’s session.

Whenever client need to session start, the sever generate a unique id called session id. This session id is sent back to the client. Whenever the client send request to the server it also sends it own session id. The server then verify the session id against its own repository. If the id is valid and not invalidated the server provides the allocated resource to the client.

HttpSessi

on

Page 61: The java enterprise edition (Servlet Basic)

HttpSession is an interface in javax.servlet.http package. When the client first interact with the server it does not have the session id. The server tries to fetch the session id from the request. If the id is NOT available then the server will create a session object and generate the session id. And that is why the HttpServletRequest interface provides two method to retrieve and create the session.

HttpSessi

on contd.

Sl. No. Method Name Description

1. HttpSession getSession() Always create a new session object. It does not check whether session id is present or not

2. HttpSession getSession(boolean create)

If the create is true then a new session object is created. Otherwise the session object is retrieved from the request.

Page 62: The java enterprise edition (Servlet Basic)

Here is the code snippet to show how to create a session.

protected void doGet(…… request, ….. response) throws ….

{

// If this is the first request for maintaining the sesion.

HttpSession s=request.getSession(); // A session object is created and id is generated.

.

.

.

}

HttpSessi

on contd.

Page 63: The java enterprise edition (Servlet Basic)

Here is the code snippet to show how to create a session.

protected void doGet(…… request, ….. response) throws ….

{

// for subsequent request from client

HttpSession s=request.getSession(false); // An old session is fetched from the request.

.

.

.

}

HttpSessi

on contd.

Page 64: The java enterprise edition (Servlet Basic)

The HttpSession interface provides some important methods.

HttpSessi

on contd.

Sl. No. Method Name Description

1. void setAttribute(String key, Object value)

Set any java object in the session object. This java object will remain in the session until either session is invalidated or server explicitly call removeAttribute

2. Object getAttribute(String key)

Returns the java object set in the session with key.

Page 65: The java enterprise edition (Servlet Basic)

HttpSessi

on contd.

Sl. No. Method Name Description

3. void removeAttribute(String key)

Remove the object associated with key from the session object.

4. void setMaxInactiveInterval(int age)

This method set the maximum time span in seconds for which the client may remain inactive. If the time span laspe the session object is destroyed.

5. void invalidate() Forcefully destroy the session.

Page 66: The java enterprise edition (Servlet Basic)

JEE framework two ways to set the inactive age for the session object.

1. Using the setMaxInactiveInterval(int age) method of HttpSession interface. Example :

protected void doGet(……. req, ……. resp) throws ….

{

HttpSession hs = req.getSession();

hs.setMaxInactiveInterval(3* 60); // set the inactive age of session as 3 min.

}

This configuration is available to one type of session. It is possible that other client may have different setting for session object.

HttpSessi

on contd.

Page 67: The java enterprise edition (Servlet Basic)

2. Using web.xml

<web-app…..>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

</web-app>

Here the 30 represent 30 min and NOT 30 sec. This configuration is valid for every session object.

HttpSessi

on contd.


Recommended