1. This scope is maintained by HttpSession object
  2. This scope will start at the time of session object creation and ends once session expires(either by timeout or by invalidate() method)
  3. The information stored in session scope is by default available to all components which are part of that session.

HttpSession interface defines the following methods for attribute management in Session scope.

  1. public void setAttribute(String name,Object value)
  2. public Object getAttribute(String name)
  3. public void removeAttribute(String name)
  4. public Enumeration getAttributeNames()

Note:Once Session expires we are not allowed call the above methods,otherwise we will get RuntimeException Saying IllegalStateException.

Example:

Display number of requests in current session
  1. Create servlet that extends HttpServlet
  2. Create web.xml
  3. Create war file and deploy web application
  4. Output of web application
  5. Download web application

Create servlet

package com.java2learn;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RequestsInSession extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();

		Integer count = (Integer) session.getAttribute("reqCount");

		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		session.setAttribute("reqCount", count);
		out.println("no.of requests in the current session" + "----" + count);
	}
}

Create web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>WebApp</display-name>

	<servlet>
		<servlet-name>RequestsInSession</servlet-name>
		<servlet-class>com.java2learn.RequestsInSession</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>RequestsInSession</servlet-name>
		<url-pattern>/requestInSession</url-pattern>
	</servlet-mapping>
</web-app>

Final application structure

FinalApplicationSession

Create war file and deploy the application

Output:
requestsinSession

Download Project: WebApp