Sesion Servlet in Java

Introduction

A Session is a period of a user's interaction with the server. Whenever a user
accesses any page of the server, then the server creates session for the user.
The server provides a unique id to each session called session id. The
session of the user remains active while the user keeps on interacting with the
server. If the user does not interact with the server for a period of 30 min
then the session gets destroyed. This period is called the default inactive
interval. The server can change the period for the default inactive interval. If the
user closes the browser then the session also gets destroyed. The server can
destroy the session of the user explicitly. A servlet can use the session of user to
create some variables. These variables occupy server memory. Users
cannot deny creation of session variables. One servlet can create session
variables and other servlets can fetch or change the value of session variables.

Creation and reading process of session

Servlet must be a sub class of HttpServlet.

Create the reference ofjavax.servlet.http.httpsession by using getSession() method ofHttpservletRequest

Use set attribute method of Httpsession tocreate session variables. Use getAttribute() of Httpsession to find value ofsession variables.

Method of HTTP session

1. Public void setAttribute(string variable name,object value)
This creates a variable within the user's session

2. Public object getAttribute(string variable name)
This returns the value of the specified session variable. If the specified variable
dose not exist in the user session then it returns null.

3. Public void invalidate();
It destroys all the variables present in the user's session

4. Public void setMaxInactiveInterval(long seconds)
It changes the default period of the Inactive interval.

Example

This servlet will accept a set of numbers one by one
infinitely and display the summation result below to the form after each
submission of the number