Sunteți pe pagina 1din 24

Difference between java applet & servlets.

1)Java Applet is a kind of application that running on the client's browser, when
a browser request a applet embedded page, the applet will downloaded to the
client computer and executed within the browser.

Servlets is a application that running on the server, when a server receive a


request of a servlet, the server will process the servlet and give the result to the
client back after the servlet is done.

2) The main difference between Applet and servlet is , Applet is an client side
program that program we can run inside of client , the Application is transmitted
over the internet . With the help of server only we can run the servlet program
,But the Applet we need not any server..

3) Applets can run under any web server their execution is dependent on Client
as they require JRE Whereas Servlets do not require any thing specific at client
side as they require java enabled web/application Server

4) Servlets have no graphical user interface whereas Applets have GUI.

5) An applet is a small program that is intended not to be run on its own but
rather to be embedded inside another application. Applets usually have some
form of user interface or perform a particular piece of the overall user interface
in a web page. This distinguishes them from a program written in a scripting
programming language (such as JavaScript) that also runs in the context of a
larger client program but which would not be considered an applet.
Where as The Java Servlets API allows a software developer to add dynamic
content to a web server using the Java platform. A servlet is an object that
receives requests and generates a response based on the request. The API
defines HTTP subclasses of the generic servlet requests and responses as well as
an HTTP session object that tracks multiple requests and responses between the
web server and a client. Servlets may be packaged as a Web application.

1
Difference between cookies and sessions:

The main difference between cookies and sessions is that cookies are stored in
the user's browser, and sessions are not. This difference determines what each is
best used for.
A cookie can keep information in the user's browser until deleted. If a person
has a login and password, this can be set as a cookie in their browser so they do
not have to re-login to your website every time they visit. You can store almost
anything in a browser cookie. The trouble is that a user can block cookies or
delete them at any time. If, for example, your website's shopping cart utilized
cookies, and a person had their browser set to block them, then they could not
shop at your website.
Sessions are not reliant on the user allowing a cookie. They work instead like a
token allowing access and passing information while the user has their browser
open. The problem with sessions is that when you close your browser you also
lose the session. So, if you had a site requiring a login, this couldn't be saved as
a session like it could as a cookie, and the user would be forced to re-login every
time they visit.
You can of course get the best of both worlds! Once you know what each does,
you can use a combination of cookies and sessions to make your site work
exactly the way you want it to.

RequestDispatcher object

A RequestDispatcher object can forward a client's request to a resource or


include the resource itself in the response back to the client. A resource can be
another servlet, or an HTML file, or a JSP file, etc.
You can also think of a RequestDispatcher object as a wrapper for the resource
located at a given path that is supplied as an argument to the
getRequestDispatcher method.
For constructing a RequestDispatcher object, you can use either the
ServletRequest.getRequestDispatcher() method or the
ServletContext.getRequestDispatcher() method. They both do the same thing,
but impose slightly different constraints on the argument path. For the
ServletRequest.getRequestDispatcher() , it looks for the resource in the same
webapp to which the invoking servlet belongs and the pathname specified can be
relative to invoking servlet.
For the ServletContext.getRequestDispatcher() method, the pathname must
begin with '/' and is interpreted relative to the root of the webapp.

2
To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both
in the same directory, you could accomplish this by incorporating the following
code fragment in either the service method or the doGet method of Servlet_A:

RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");

dispatcher.forward( request, response );

where request, of type HttpServletRequest, is the first parameter of the enclosing


service method (or the doGet method) and response, of type
HttpServletResponse, the second. You could accomplish the same by

RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );

dispatcher.forward( request, response );

sendRedirect method:

When we want that someone else should handle the response of our servlet, then
there we should use sendRedirect() method.

In send Redirect whenever the client makes any request it goes to the container,
there the container decides whether the concerned servlet can handle the request
or not. If not then the servlet decides that the request can be handle by other
servlet or jsp. Then the servlet calls the sendRedirect() method of the response
object and sends back the response to the browser along with the status code.
Then the browser sees the status code and look for that servlet which can now
handle the request. Again the browser makes a new request, but with the name
of that servlet which can now handle the request and the result will be displayed
to you by the browser. In all this process the client is unaware of the processing.

3
IMP Questions:

What is the Difference between RequestDispatcher's


forward(ServletRequest request, ServletResponse response) method and
HttpServletResponse's sendRedirect(String location) method?

(1)The forward method of RequestDispatcher will forward the ServletRequest


and ServletResponse that it is passed to the path that was specified in
getRequestDispatcher(String path). The response will not be sent back to the
client and so the client will not know about this change of resource on the
server. This method is useful for communicating between server resources,
(servlet to servlet). Because the request and response are forwarded to another
resource all request parameters are maintained and available for use. Since the
client does not know about this forward on the server, no history of it will be
stored on the client, so using the back and forward buttons will not work. This
method is faster than using sendRedirect as no network round trip to the server
and back is required.

An example using forward:

protected void doGet(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException

{
RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
rd.forward(request, response);

The sendRedirect(String path) method of HttpServletResponse will tell the


client that it should send a request to the specified path. So the client will build a
new request and submit it to the server, because a new request is being
submitted all previous parameters stored in the request will be unavailable. The
client's history will be updated so the forward and back buttons will work. This
method is useful for redirecting to pages on other servers and domains.

4
An example using sendRedirect: protected void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException{
response.sendRedirect("pathToResource");
}

(2) sendRedirect() is more flexible than forward() because with sendRedirect()


you can connect to any URL outside the webapplication whereas forward() will
work only within the web application.

(3) Forward

Since forward() method of RequestDispatcher is handled on the server ,


therefore the request and its associated session are available to the forwarded
resource and you can pass data between them using request.setAttribute().
forward() separates the responsibilities for handling the requests among several
components. This method generally sends a request and response object to
resources (servlets or JSP's) of the same ServletContext. You can also decide to
forward to one page in one condition and a different page in another.
RequestDispatcher transfers control immediately whenever the forward()
method is called to the resource referenced by the RequestDispatcher.

sendRedirect

sendRedirect() method of a response object sends the url to the browser that
includes the parameter of sendRedirect() method Browser treats this a new
request from the client. sendRedirect() forwards a requests to a resource outside
of the current web application. Using sendRedirect is similar to open a new
browser and type your url. A sendRedirect() also updates the browser history
and transfers control only when the whole service method completes.

5
Servlet Container(Servlet Engine)

The servlet container is a compiled, executable program. The container is the


intermediary between the Web server and the servlets in the container. The
container loads, initializes, and executes the servlets. When a request arrives, the
container maps the request to a servlet, translates the request into objects, and
then passes the request to the servlet. The servlet processes the request and
produces a response. The container translates the response into the network
format, then sends the response back to the Web server.

The container is designed to perform well while serving large numbers of


requests. A container can hold any number of active servlets, filters, and
listeners. Both the container and the objects in the container are multithreaded.
The container creates and manages threads as necessary to handle incoming
requests. The container handles multiple requests concurrently, and more than
one thread may enter an object at a time. Therefore, each object within a
container must be thread safe.

Figure 1 presents a diagram of a running container. In the diagram, the container


has a single network connector. The container manages two contexts, each of
which contains a number of objects.

Figure 1: Container diagram

6
Network Connectors

The servlet container receives requests through a network connector. Typically,


the connector communicates with a Web server, although the container itself
provides a miniature Web server for testing purposes. A servlet itself need not
interact with the network. The container handles the details of the network
connection. A servlet handles all requests in the same way, regardless of how
the request arrived in the container.

The container includes network connectors for two different protocols:

• The AJP13 protocol is widely used for communication


between Web servers and servlet containers. The Tomcat includes ready-built
AJP13 plug-ins for the Apache and IIS Web servers.
• Web servers and clients communicate using HTTP. The
container includes a miniature HTTP server for development and testing
purposes.

A running container may use any number of these connectors, in any


combination. The container configuration determines which connectors the
container uses.

Contexts

A servlet container can manage any number of distinct applications. An


application consists of any number of servlets, filters, listeners, and static Web
pages. A set of components working together is a Web application. Tomcat does
not directly represent the concept of a Web application. Instead, the container
uses a context to group related components. The container loads the objects
within a context as a group, and objects within the same context can easily share
data. Therefore, each context usually corresponds to a distinct Web application.

The container command line must provide the location of a directory that holds
descriptions of the servlets, listeners, and filters that the container loads. This
directory is the webapps directory for the container. Each directory within the
webapps directory defines a context. The name of the context directory is the
name of the context and determines the path to the servlets within the context.
Each context directory contains a WEB-INF directory, and may also contain
files related to the application. Each WEB-INF directory contains a web.xml

7
file. The web.xml file describes the configuration of the context and the servlets,
filters, and listeners that occupy the context.

For example, the directory structure below describes two contexts, one named
orders and one named catalog. The catalog context contains a static HTML
page, intro.html.

webapps
\orders
\WEB-INF
web.xml
\catalog
intro.html
\WEB-INF
web.xml

If the container is at http://example.com/servlets/, an HTML page at


webapps\catalog\intro.html appears at the URL
http://example.com/servlets/catalog/intro.html. Likewise, servlets defined in the
webapps\orders\WEB-INF\web.xml file appear at URLs underneath
http://example.com/servlets/orders.

ServletContext

ServletContext is a interface which helps us to communicate with the servlet


container. There is only one ServletContext for the entire web application and
the components of the web application can share it. The information in the
ServletContext will be common to all the components. Remember that each
servlet will have its own ServletConfig. The ServetContext is created by the
container(also called Servlet Engine) when the web application is deployed and
after that only the context is available to each servlet in the web application.

Web application initialization:

1. First of all the web container reads the deployment


descriptor

file and then creates a name/value pair for each <context-param> tag.

8
2. After creating the name/value pair it creates a new
instance of ServletContext.
3. Its the responsibility of the Container to give the
reference of the ServletContext to the context init parameters.
4. The servlet and jsp which are part of the same web
application can have the access of the ServletContext.

The Context init parameters are available to the entire web application
not just to the single servlet like servlet init parameters.

How can we do the mapping of the Context init parameters in web.xml

<servlet>
<servlet-name>Mapping</servlet-name>
<servlet-class>ContextMapping</servlet-class>
</servlet>

<context-param>
<param-name>Email</param-name>
<param-value>admin@roseindia.net</param-value>
</context-param>

In the servlet code we will write this as

ServletContext context = getServletContext();


pw.println(context.getInitParameter("Email");

1. Overview of Cookies

Cookies are small bits of textual information that a Web server sends to
a browser and that the browser returns unchanged when visiting the
same Web site or domain later. By having the server read information it
sent the client previously, the site can provide visitors with a number of
conveniences:

• Identifying a user during an e-commerce session.


Many on-line stores use a "shopping cart" metaphor in which the user
selects an item, adds it to his shopping cart, then continues shopping.
Since the HTTP connection is closed after each page is sent, when the

9
user selects a new item for his cart, how does the store know that he is
the same user that put the previous item in his cart? Cookies are a good
way of accomplishing this. In fact, this is so useful that servlets have an
API specifically for this, and servlet authors don't need to manipulate
cookies directly to make use of it. This is discussed in the tutorial
section on Session Tracking.
• Avoiding username and password. Many large sites
require you to register in order to use their services, but it is
inconvenient to remember the username and password. Cookies are a
good alternative for low-
• security sites. When a user registers, a cookie is sent
with a unique user ID. When the client reconnects at a later date, the
user ID is returned, the server looks it up, determines it belongs to a
registered user, and doesn't require an explicit username and password.
• Customizing a site. Many "portal" sites let you
customize the look of the main page. They use cookies to remember
what you wanted, so that you get that result initially next time. I'll give
an example like this later in this section of the tutorial.
• Focusing advertising. The search engines charge
their customers much more for displaying "directed" ads than "random"
ads. That is, if you do a search on "Java Servlets", a search site can
charge much more for an ad for a servlet development environment
than an ad for an on-line travel agent. On the other hand, if the search
had been "Bali Hotels", the situation would be reversed. The problem is
that they have to show a random ad when you first arrive and haven't
yet performed a search, as well as when you search on something that
doesn't match any ad categories. Cookies let them remember "Oh, that's
the person who was searching for such and such previously" and
display an appropriate (read "high priced") ad instead of a random (read
"cheap") one.

Now, providing convenience to the user and added value to the site
owner is the purpose behind cookies. And despite much
misinformation, cookies are not a serious security threat. Cookies are
never interpreted or executed in any way, and thus can't be used to
insert viruses or attack your system in any way. Furthermore, since
browsers generally only accept 20 cookies per site and 300 cookies
total, and each cookie is limited to 4KB, cookies cannot be used to fill
up someone's disk or launch other denial of service attacks. However,
even though they don't present a serious security threat, they can

10
preseent a significant threat to privacy. First, some people don't like the
fact that search engines can remember that they're the person that
usually does searches on such and such a topic. For example, they
might search for job openings or health data, and don't want some
banner ad tipping off their coworkers next time they do a search. Even
worse, two search engines could share data on a user by both loading
small images off a third party site, where that third party uses cookies
and shares the data with both search engines. (Netscape, however,
provides a nice feature that lets you refuse cookies from sites other than
that to which you connected, but without disabling cookies altogether.)
This trick can even be exploited via email if you use an HTML-enabled
email reader that "supports" cookies, as Outlook Express does. Thus,
people could send you email that loads images, attach cookies to those
images, then later identify you (email address and all) when you went
to their site.

Or, a site that ought to have much higher security standards might let
users skip user name and passwords via cookies. For example, some of
the big on-line bookstores use cookies to remember users, and let you
order without reentering much of your personal information. However,
they don't actually display the full credit card number, and only let you
send books to an address that was entered when you did enter the credit
card in full or use the username and password. As a result, someone
using the person's computer (or stealing their cookie file) could do no
more harm than sending a big book order to the credit card owner's
address, where it could be refused. However, smaller companies might
not be so careful, and access to someone's computer or cookie file
could result in loss of valuable personal information. Even worse,
incompetent sites might embed credit card or other sensitive
information directly in the cookies themselves, rather than using
innocuous identifiers which are only linked to real users on the server.

The point of all this is twofold. First, due to real and perceived privacy
problems, some users turn off cookies. So, even when you use cookies
to give added value to a site, your site shouldn't depend on them.
Second, as the author of servlets that use cookies, you should be careful
not to trust cookies for particularly sensitive information, since this
would open the user up to risks if somebody accessed their computer or
cookie files.

11
2. The Servlet Cookie API

To send cookies to the client, a servlet would create one or more


cookies with the appropriate names and values via new Cookie(name,
value) (section 2.1), set any desired optional attributes via
cookie.setXxx (section 2.2), and add the cookies to the response
headers via response.addCookie(cookie) (section 2.3). To read
incoming cookies, call request.getCookies(), which returns an array of
Cookie objects. In most cases, you loop down this array until you find
the one whose name (getName) matches the name you have in mind,
then call getValue on that Cookie to see the value associated with that
name. This is discussed in section 2.4.

2.1 Creating Cookies

A Cookie is created by calling the Cookie constructor, which takes two


strings: the cookie name and the cookie value. Neither the name nor the
value should contain whitespace or any of:
[]()=,"/?@:;

2.2 Reading and Specifying Cookie Attributes

Before adding the cookie to the outgoing headers, you can look up or
set attributes of the cookie. Here's a summary:
getComment/setComment
Gets/sets a comment associated with this cookie.
getDomain/setDomain
Gets/sets the domain to which cookie applies. Normally, cookies are
returned only to the exact hostname that sent them. You can use this
method to instruct the browser to return them to other hosts within the
same domain. Note that the domain should start with a dot
(e.g. .prenhall.com), and must contain two dots for non-country
domains like .com, .edu, and .gov, and three dots for country domains
like .co.uk and .edu.es.
getMaxAge/setMaxAge
Gets/sets how much time (in seconds) should elapse before the cookie
expires. If you don't set this, the cookie will last only for the current
session (i.e. until the user quits the browser), and will not be stored on

12
disk. See the LongLivedCookie class below, which defines a subclass
of Cookie with a maximum age automatically set one year in the future.
getName/setName
Gets/sets the name of the cookie. The name and the value are the two
pieces you virtually always care about. Since the getCookies method of
HttpServletRequest returns an array of Cookie objects, it is common to
loop down this array until you have a particular name, then check the
value with getValue. See the getCookieValue method shown below.
getPath/setPath
Gets/sets the path to which this cookie applies. If you don't specify a
path, the cookie is returned for all URLs in the same directory as the
current page as well as all subdirectories. This method can be used to
specify something more general. For example, someCookie.setPath("/")
specifies that all pages on the server should receive the cookie. Note
that the path specified must include the current directory.
getSecure/setSecure
Gets/sets the boolean value indicating whether the cookie should only
be sent over encrypted (i.e. SSL) connections.
getValue/setValue
Gets/sets the value associated with the cookie. Again, the name and the
value are the two parts of a cookie that you almost always care about,
although in a few cases a name is used as a boolean flag, and its value
is ignored (i.e the existence of the name means true).
getVersion/setVersion
Gets/sets the cookie protocol version this cookie complies with.
Version 0, the default, adheres to the original Netscape specification.
Version 1, not yet widely supported, adheres to RFC 2109.

2.3 Placing Cookies in the Response Headers

The cookie is added to the Set-Cookie response header by means of the


addCookie method of HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);

2.4 Reading Cookies from the Client

To send cookies to the client, you created a Cookie then used


addCookie to send a Set-Cookie HTTP response header. This was
discussed above in section 2.1. To read the cookies that come back

13
from the client, you call getCookies on the HttpServletRequest. This
returns an array of Cookie objects corresponding to the values that
came in on the Cookie HTTP request header. Once you have this array,
you typically loop down it, calling getName on each Cookie until you
find one matching the name you have in mind. You then call getValue
on the matching Cookie, doing some processing specific to the resultant
value. This is such a common process that the following section
presents a simple getCookieValue method that, given the array of
cookies, a name, and a default value, returns the value of the cookie
matching the name, or, if there is no such cookie, the designated default
value.

Managing Sessions with Java Servlets

What is a Session ?
A session is pretty much what it sounds, when a user makes a page
request to the server, the server creates a temporary session to identify
that user. So when that same user goes to another page on that site, the
server identifies that user. So a session is a small and temporary unique
connection between a server and the user enabling it to identify that
user across multiple page requests or visits to that site.

What is Session Management ?


Ok now you know what is a session. Session management is to use the
API provided by your application server to identify the user across
multiple page requests. Note that every server has it's own set of API
for session management, since we are talking about 'Managing Sessions
with Java Servlets', we will be making use of the Servlet API 2.2 which
almost all of the Java application servers support.

Why use Session Management ?


Hundreds and thousands of simultaneous users can be visiting your site
and if you can identify each of them separately then it can provide
tremendous benefits to you. Following are only some of the uses which
have come to my mind :

14
• Customizations : Your can allow site visitors to
customize the look and feel of your site, thus show each user a different
view of your site. You can also show different content to different users
depending on their preferences. I am also thinking about adding
customization features to Stardeveloper.com which will allow you to
change the layout, color schemes, fonts etc according to your own
liking.
• Security : You can allow membership based access
to your site thus making sure that only members get to see special
content on your site. After logging in you can identify members from
non-members by setting an attribute on the user session to some value.
Thus no need to log in again and again.
• User Behavior : You can log user behavior like how
many ad views have been shown to the user. If lot have been shown
with no response from the user then it is time to change that ad. This is
a great feature really, if you are into making an ad rotation software
you can count how many ad views of which advertiser have been
shown to the user and if user doesn't click through then better change
that ad with some other one instead of wasting ad views of the same ad
on this user.

Servlet API interface required for session management:

HttpSession Interface: Managing sessions has been made extremely


easy by the Servlet API since there is just a single interface involved
and that interface is HttpSession interface. You then invoke methods of
this interface to interact with the user.

Methods of HttpSession Interface


Before going into the details of using different methods of this
interface, lets first see what are different methods available to us.

• getAttribute(), getAttributeNames(),
setAttribute(), removeAttribute() These methods are used to set, get
and remove objects from a user session. We will see later how to use
them.
• getId() Every session created by the server has a
unique 'id' associated with it in order to identify this session from other
sessions. This method returns the 'id' of this session.

15
• getCreationTime() Simple returns a long value
indicating the date and time this session was created, meaning there by
that you get the time this user first accessed your site.
• getLastAccessedTime() Returns a long value
indicating the last time user accessed any resource on this server.
• getMaxInactiveInterval(),
setMaxInactiveInterval() Return and set the maximum inactive
interval in seconds for this session respectively. Note that every session
has a maximum inactive interval during which if user doesn't make
request to the server, his session is invalidated.
• isNew() Returns a boolean value indicating if the
session is new. It means that either it is the first page of the site user
has hit so his session is new and has just been created or that user is not
accepting cookies required for managing sessions so this value will
then always return true.
• invalidate() Simply invalidates a session. You can
use this method on a 'logout' page allowing user to end his session. If
after invalidation of his session user accesses some resource on the site
then a new session will be created for it. You must have seen this
'logout' feature which ends your session on some of the free email sites
on the web, so you understand how useful this method is.

It is time now to actually build an example Servlet which demonstrates


the methods we just learned. This is what we are going to do on the
next page, build a simple Servlet which will track number of times this
Servlet has been seen by the user. In this example you will also learn
how to bind objects to a user session, this is very important as most
often than not you will be working with session level objects.

SessionDemo.java
The application we are going to build will demonstrate the use of
almost all of the methods of HttpSession interface discussed on the last
page.

Overview of the Demo Application.


We will first build a simple Java class 'Counter'. This class will be
responsible for keeping count of pages viewed by the user. We will
then build a Servlet which will use HttpSession.setAttribute() method
to bind this Counter object to the user session. So every user will have

16
a different session and thus every session will have a different Counter
object attached to it.

Counter Class
Copy and paste the following code into a new .java file and save it as
'Counter.java' in the

import java.io.Serializable;

public class Counter implements Serializable {

private int count = 0;

public int getCount() {


return this.count;
}

public void increment() {


this.count++;
}
}

Explanation
Above is a simple Java class which contains a private int variable
named 'count'. Then there are two methods, one getter and the second
one ( increment() ) increments the internal variable 'count' by 1.
getCount() will return the value of 'count' variable that is the number of
pages user has viewed. Now compile 'Counter.java' file and make sure
that it is in the right folder ( see above ).

We are done with 'Counter' class so lets move forward to build our
Servlet which will bind this class to the user session and keep track of
the number of times page has been viewed and will also display some
other useful information about the session to the user.

17
TestSessionServlet
We will name our Servlet 'TestSessionServlet'. Create a new .java file,
copy and paste the following code in it. Save it as
'TestSessionServlet.java' in the

import java.io.*;

import java.util.Date;

import javax.servlet.*;

import javax.servlet.http.*;

public class TestSessionServlet extends HttpServlet {

public void doGet(HttpServletRequest req,


HttpServletResponse res)

throws IOException, ServletException {

res.setContentType("text/html");

// got hold of the user session

18
PrintWriter out = res.getWriter();

HttpSession session = req.getSession(true);

// declare out Counter object

Counter counter;

if(session.isNew()) {

counter = new Counter();

session.setAttribute("counter",
counter);

// incrementing page view count in our


Counter object

counter =
((Counter)session.getAttribute("counter"));

counter.increment();

// retrieving session info

19
long currentTime =
System.currentTimeMillis();

long creationTime =
session.getCreationTime();

long lastAccessed =
session.getLastAccessedTime();

long maxInterval =
session.getMaxInactiveInterval();

String sessionId = session.getId();

String mode = req.getParameter("mode");

// print content

out.print("<html><head>");

out.print("<style>body, p { font-
family:tahoma;");

out.print("font-size:12pt; } a { text-
decoration:none;");

out.print("color:blue; }</style></head>");

out.print("<body>");

20
if(session.isNew()) {

out.print("<p>New Session
created.</p>");

} else {

out.print("<p>Old Session. ");

out.print("Age : ");

out.print( (currentTime -
creationTime) / 60000 );

out.print(" minutes.</p>");

out.print("<p>You have visited this page :


");

out.print( counter.getCount() );

out.print(" times.<br>");

out.print("Created at : ");

out.print( new Date(creationTime) );

out.print("<br>");

out.print("Last accessed : ");

out.print( new Date(lastAccessed) );

21
out.print("<br>");

out.print("SessionID : ");

out.print( sessionId );

out.print("</p><p>");

out.print("Note! Session will be inactivated


after ");

out.print("a period of inactivity of <b>");

out.print( (maxInterval / 60) );

out.print("</b> minutes.");

out.print("</p><p>");

if( mode != null &&


mode.equals("invalidate")) {

session.invalidate();

out.close();

22
}

Explanation
Above code is extremely simple. Our TestSessionServlet class extends
HttpServlet class and overrides just one method, doGet(). In this
method we first get a reference to PrintWriter object to write content
back to the client. Next we get reference to the user session using
HttpServletRequest interface's getSession() method.

Then we declare our Counter object and if the session is new then
create a new Counter object and bind it to the user using setAttribute()
method we learned earlier.

Then we get reference to our Counter object from the user session
using getAttribute() method and increment the page view count by 1.

Next we declare different variables to receive different values from the


user session. Then we output plain HTML to the user along with
session info we obtained. simple!

Once finished we close the PrintWriter object.

Tips
Following are some of the tips which I think will be helpful to you
when programming session management :

• Primitive data types cannot be bound to user


session : Most people make the mistake of binding primitive data types
like int etc to the user session. This is not possible and you will get a
translation-time error. HttpSession interface only allows objects to be
bound to the session. So keep this in mind and stay away from trouble.
• Smaller the object the better it is : Since session
may be required to be maintained across multiple servers, it is better
that the size of objects bound to it remain small. Learn from the
Counter class we made earlier, see how small memory footprint it had.

23
• Make sure session level objects implement
Serializable interface It is imperative that you understand this. All
session level objects must implement Serializable interface because if
your site spans multiple servers then the session level objects will not
be ported to the other server. So in order to properly track user session
along with all the bounded objects across multiple servers ( server farm
), your classes must implement Serializable interface.

24

S-ar putea să vă placă și