TechWriterDev
  • Cloud
    • AWS
      • 00_Doubts
      • CloudPractitioner
        • Cloud Computing
        • AWS Global Infrastructure
        • Introduction to AWS EC2
        • Elastic load balancer(ELB)
        • 04_Messaging_Queuing
        • Aditional Computing Service
        • Accessing AWS resources
        • AWS Networking
        • Storage
        • Amazon Database Solutions
        • Monitoring Tools
        • AWS Security
        • Distributed Denial Of Service Attacks
      • DeveloperAssociate
        • References
        • AWS DVA-C02 Services Index
        • Services
          • 00_IAM
            • Identity and Access Management (IAM)
            • Account Protection Mechanisms
            • Access Mechanism of AWS Resources
            • Security Tools
            • Responsibility Model
            • Advanced Concepts
          • 01_EC2
            • Elastic Compute Cloud (EC2)
            • EC2 Volume Types
            • Amazon Machine Image (AMI)
            • AWS charges for IPv4 address
          • 02_SecurityGroups
            • Security Groups
          • 03_Elastic_LoadBalancing
            • Terminology
            • Elastic load balancer
            • Features
            • Basics
          • 04_AutoScaling
            • Auto Scaling
          • 05_RDS
            • Relational Database Service (RDS)
            • Aurora
            • Security
            • RDS Proxy
          • 06_ElastiCache
            • Cache
            • Cache Offerings
          • 07_Route53
            • Basics of DNS
            • Route 53
          • 08_VPC
            • Virtual Private Cloud (VPC)
          • 09_S3
            • Simple Storage Service (S3)
            • S3 Features
            • S3 Encryption
            • S3 Features
            • S3 Bucket Policy and IAM Policy
          • 10_ECS
            • Elastic Container Service (ECS)
            • Elastic Container Registry (ECR)
            • AWS Copilot
          • 11_EKS
            • Elastic Kubernetes Service (EKS)
          • 12_SDK_CLI_Tips
            • Access AWS Resources
          • 13_CloudFront
            • Cloud Front
          • 14_Messaging
            • Simple Queue Service (SQS)
            • Simple Notification Service (SNS)
            • Fan Out Pattern
            • Kinesis
            • Compare and Contrast
          • 15_ElasticBeanStalk
            • Elastic Beanstalk
          • 16_CloudFormation
            • CloudFormation
            • Dynamic References
          • 17_Monitoring
            • AWS Monitoring
            • AWS CloudWatch
            • CloudWatch Alarms
            • Synthetics Canary
            • Amazon EventBridge (formerly CloudWatch Events)
            • X-Ray
            • OpenTelemetry
            • CloudTrail
          • 18_Lambda
            • Lambda
            • Lambda Integrations
            • Configuring Lambda
            • Lambda Layers
          • 19_API_Gateway
            • API Gateway
            • API Gateway Integrations
          • 20_DynamoDB
            • DynamoDB
            • Operations
            • Indexes
            • DynamoDB Accelerator (DAX)
            • DynamoDB Streams
            • Transactions
            • Integrations
          • 21_CICD
            • CICD
            • CodeCommit
            • CodePipeline
            • CodeBuild
            • CodeDeploy
            • CodeArtifact
            • CloudGuru
          • 22_SAM
            • Serverless Application Model (SAM)
          • 23_CDK
            • Cloud Development Kit (CDK)
          • 24_StepFunctions
            • Step Functions
            • Types of step function
          • 25_AppSync
            • AppSync
          • 26_Amplify
            • Amplify
          • 27_STS
            • Security Token Service (STS)
          • 28_DirectoryService
            • Active Directory
          • 29_KMS
            • Encryption
            • KMS API
            • Features
            • Cloud Hardware Security Module (HSM)
          • 30_SSM_Store
            • SSM Parameter Store
          • 31_SecretsManager
            • Secrets Manager
          • 32_Cognito
            • Cognito
      • Questions
        • AWS_Region
        • EC2
        • IAM
  • Database
    • MongoDb
      • Mongo db Basics
      • Mongo DB Atlas
      • Document
      • Import-Export based on Data Format
      • Mongo Shell Commands
      • Query Operators
      • Indexes
      • Upsert
      • MongoDB Aggregation Framework
      • Aggregation Framework Operators
    • PostgreSQL
      • POSTGRE SQL DataTypes
      • About table
      • Constraints
  • Technologies
    • RabbitMQ
      • RabbitMQ Concepts
      • Introduction to Exchanges
      • Introduction to Queues
    • Terraform
      • 00_Introduction
      • Configuration blocks
      • Commands
      • Variables
      • Terraform Cloud
      • Modules
  • Languages
    • Java
      • Logging
        • Getting Started
      • 00_Core
        • 00_Basics
          • Java Vs C++
          • Object oriented principles
          • Steps to compile a java program
          • JVM Internals
          • Understanding Java Development Kit
          • What is JIT Compiler?
          • Java data types
          • 07_identifiers_type_conversion
          • 08_references_and_packages
          • Steps for attaching scanner
        • Concurrency
          • 00_Threads
            • Threads
          • 01_ExecutorFramework
            • Executor Framework
            • Asynchronous Computation
      • 01_Backend
        • 01_HttpAndWebServerBasics
          • HTTP
          • Content Type
          • Web Server
        • 02_J2EE_Basics
          • J2EE_Basics
          • Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?
        • 03_TomCatAndSession
          • What is a Session?
          • WebContainer
        • 04_PageNavigation
          • Cookies Additional Information
          • Page Navigation Techniques
        • 05_AboutServlet
          • CGI v/s Servlet
          • Executor Framework
          • Servlet Life cycle
          • SERVLET CONFIG
          • Servlet Context
          • Servlet Listener (web application listener)
        • 08_SpringBoot
          • Spring Boot
          • Some common annotations used in spring eco system
        • 09_SpringDataJPA
          • Spring Data JPA
        • Java_Language_Changes
          • JDK enhancement tracking reference
        • 06_ORM_Hibernate
          • readmes
            • Hibernate
            • Advantages of Hibernate
            • Hibernate Caching
            • Hibernate API
            • Hibernate Query API
            • Hibernate Annotations and JPQL
            • Entity and Value Type
        • 07_SpringFramework
          • bean_validation
            • Bean Validation
          • core
            • readme
              • Spring
              • Spring Framework Modules
              • Spring MVC Request flow
              • Dependency Injection
              • Spring Beans
              • 06_Spring_Framework_Annotations
      • 03_Tools
        • Maven
          • Maven
  • SoftwareEngineering
    • DesignPatterns
      • Notes
        • Basics
        • OOP
        • SOLID Principles
        • 03_Creational
          • Abstract Factory (aka Kit)
          • Builder
          • Factory Method (aka Virtual constructor)
          • Prototype
          • Singleton
        • 04_Structural
          • Adapter (aka Wrapper)
          • Bridge (aka Handle | Body)
          • Composite
          • Decorator (aka Wrapper)
          • Facade
          • Flyweight
          • Proxy (aka Surrogate)
        • 05_Behavioral
          • Chain of Responsibility
          • Command (aka Action | Transaction)
          • Iterator (aka Cursor)
          • Observer (aka Publish-Subscribe | Dependents)
          • Strategy (aka Policy)
    • Principles
      • REST
        • REST
  • Tools
    • Containers
      • Docker
        • Docker
        • Docker Image
        • Commands
        • Compose
        • Best Practices
      • Kubernetes
        • Kubernetes
    • VCS
      • Git
        • Quick reference of useful Git commands
Powered by GitBook
On this page
  • What is the need of session tracking?
  • Techniques for session tracking.
  • Plain Cookie
  • Disadvantages of pure cookie based scenario
  • HttpSession
  1. Languages
  2. Java
  3. 01_Backend
  4. 03_TomCatAndSession

What is a Session?

  • Session is a conversional state between client and server that consists of multiple request and response between client and server.

  • Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session is passed between server and client in every request and response.

  • HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and they can't identify if its coming from client that has been sending request previously.

  • But sometimes in web applications, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client.

What is the need of session tracking?

  1. To identify a client uniquely among multiple clients

  2. To remember the conversational state of the client

    • eg : list of the purchased books/ shopping cart/bank acct details/stocks) throughout current session

    • session = Represents duration or time interval

    • Consists of all requests/response coming from or sent to, same client from login to logout or till session expiration timeout.


Techniques for session tracking.

  1. Plain Cookie

  2. HttpSession interface

  3. HttpSession + URL rewriting

Plain Cookie

  • What is a cookie?

    • Cookie is small amount of text data.

    • It is created by server (servlet or JSP prog or WC) & sent to client by adding them within response header(Set-Cookie header).

    • Cookie represents data shared across multiple dynamic pages from the same web application.(meant for the same client)

    • Note: In browser, the response header will have Cookie header, which contains the cookie when sending from client to server.

  • Cookie based tracking techniques fails when cookies are disabled by client.(hence other techniques)

  • When cookie based tracking is enabled, browser checks age of the cookie, on requests subsequent to initial request.

    Cookie Age
    Description

    -1

    Default value, stored temporarily in browser cache

    0

    Delete the cookie from browser

    >0 (seconds)

    Time period till which cookie is saved in the client side in hard disk in persistent manner.

  • Once cookie is created in the server, these cookies are exchanged in the subsequent requests from server to client and vice versa, hence server remembers the client.

  • Steps for cookie based tracking

// Create cookie instance
javax.servlet.http.Cookie

Cookie(String Name,String Value)

// Add the cookie/s to the response header.
// HttpServletResponse API
void addCookie(Cookie c)

// To retrieve the cookies
/**** HttpServletRequest API***********/
//returns null if no cookies found.
Cookie[] getCookies()

/*Cookie class methods*/
javax.servlet.http.Cookie 
//Cookies's name and value related API 
String getName()
String getValue()

//Cookie's age related API
void setMaxAge(int ageInSeconds)
int getMaxAge()

Response is sent once the server closes the stream at the server side.

Disadvantages of pure cookie based scenario

  1. Web developer (servlet prog) has to manage cookies.

  2. Cookies can handle only text data : storing Java object or binary data is difficult.

  3. As no of cookies increases, it will result into increased net traffic.

  4. In cookie based approach, entire state of the client is saved on the client side. If the client browser rejects/deletes the cookies, state will be lost and session tracking fails.

HttpSession

  • In this technique, entire state of the client is not saved on client side , instead it is saved on the server side data structure (Http Session object). But, the key to this Http Session object is still sent to client in form of a cookie(JSESSIONID).(cookie management is done by WC).

  • Servlet programmer can store/restore java objects directly under the session scope(setAttribute/getAttribute)

  • Above mentioned, disadvantages of cookie based tracking (points 1, 2 & 3) are solved. But entire session tracking again fails, if cookies are disabled.

  • Steps for javax.servlet.http.HttpSession i/f based session tracking.

  1. Get Http Session object from WC


  HttpServletRequest
  HttpSession getSession() 
  
  javax.servlet.http
  HttpSession<String,Object> sessionobject
  key: String
  value: Object
  //OR
  HttpSession getSession(boolean create)
  • Servlet requests WC to either create and return a new HttpSession object(for new client : JSESSIONID) or return the existing one from WC's heap for existing client (Provided server has Cookie[] present).

      Cookie name: JSESSIONID
      Cookie value: unique long string value generated per clnt
  1. To save data in HttpSession?(scope=entire session)

  javax.servlet.http.HttpSession

  //Prototype
  public void setAttribute(String name,Object Value)
  //calling
  hs.setAttribute("clnt_info",validatedCustomer);
  // attribute refers to server side object/server side entry(key and value pair) map

  //equivalent to map.put(k,v)  
  //eg : hs.setAttribute("cart",l1);
  1. For retrieving session data(getting attributes)


  //Prototype
  public Object getAttribute(String name) throws IllegalStateException
  //name: key

  //calling
  Customer cust=(Customer) hs.getAttribute("clnt_info");

A bit about attributes

  • Attributes can exist in one of 3 scopes

Scope
Visibility

Request scoped attributes

Attribute is visible for current request

Session scoped attribute

Attribute is visible for current session.(shared across multiple requests coming from SAME client)

Application scoped attribute

Visible for current web application.(shared across multiple requests from ANY client BUT for the SAME web application)

  1. To get session ID (value of the cookie whose name is JSESSIONID, which is unique per client created by WC)

  String getId()
  1. To remove attribute from the session scope?

  //prototype
  public void removeAttribute(String name)
  
  //calling
  hs.removeAttribute("clnt_info");
  1. To invalidate a session.

  //HttpSession API
  public void invalidate()
  //WC marks HS object on the server side for Garbage Collection 
  //BUT cookie is not deleted from client browser
  1. To check if the current client is senting a request for first time

  //HttpSession API
  public boolean isNew()
  //Rets true for new client & false for existing client.
  1. To find all attribute names from the session.


  public Enumeration<String> getAttributeNames()
  //rets java.util.Enumeration of attr names.

Note: default session expiration time out duration for tomcat is 30 minutes.

  1. To change session timeout.

  //HttpSession  i/f method
  
  //prototype
  public void setMaxInactiveInterval(int seconds)
  
  //calling
  hs.setMaxInactiveInterval(300); --for 5 mins .
  <!-- via xml tags in web.xml -->
  <session-config>
    <session-timeout>5</session-timeout>
  </session-config>

For ServletContext refer Day 4 regarding_servletcontext.md document.

Previous03_TomCatAndSessionNextWebContainer

Last updated 4 months ago

cookie_tracking