# 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.**<br>

***

## 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.

  ![cookie\_tracking](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-6f4ae2447b79183e062d208ac423928b9587004a%2Fcookie.png?alt=media)
* **Steps for cookie based tracking**

```java
// 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

```java

  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)

```java
  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);
```

3. For retrieving session data(getting attributes)

```java

  //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)* |

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

```java
  String getId()
```

5. To remove attribute from the session scope?

```java
  //prototype
  public void removeAttribute(String name)
  
  //calling
  hs.removeAttribute("clnt_info");
```

6. To invalidate a session.

```java
  //HttpSession API
  public void invalidate()
  //WC marks HS object on the server side for Garbage Collection 
  //BUT cookie is not deleted from client browser
```

7. To check if the current client is senting a request for first time

```java
  //HttpSession API
  public boolean isNew()
  //Rets true for new client & false for existing client.
```

8. To find all attribute names from the session.

```java

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

```

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

9. To change session timeout.

```java
  //HttpSession  i/f method
  
  //prototype
  public void setMaxInactiveInterval(int seconds)
  
  //calling
  hs.setMaxInactiveInterval(300); --for 5 mins .
```

```xml
  <!-- via xml tags in web.xml -->
  <session-config>
    <session-timeout>5</session-timeout>
  </session-config>
```

> For ServletContext refer Day 4 `regarding_servletcontext.md` document.
