# Request , Session and Context Part - 2

## Session Object vs Context Object :

### Session Object :

1. **One per user/machine**
2. **Objects available across requests**
3. **Perfect for login sessions and shopping carts**
4. **Every request object has a reference to the session object.**

![Session object is null for other user/browser](/files/-LcosU6X3XowY2UNoSX2)

### **Context Object :**

1. **Across the entire application**
2. **Shared across servlets and users**
3. **Initialization code / Common bulletin board**
4. **Use the Context object**

#### How to create session ?

```java
ServletContext context = request.getServletContext();
		if (userName != null) {
			httpSession.setAttribute("userName", userName);
			context.setAttribute("userName", userName);
		}
```

```java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Hello from Get method of XML servlet");
		response.setContentType("text/html");
		String userName = request.getParameter("userName");
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Hello from GET method using request parameter " + userName);
		//getting session
		HttpSession httpSession = request.getSession();
		//getting context
		ServletContext context = request.getServletContext();
		if (userName != null) {
			httpSession.setAttribute("userName", userName);
			context.setAttribute("userName", userName);
		}
		printWriter.println("Hello from GET method using session parameter " + httpSession.getAttribute("userName"));
		printWriter.println("Hello from GET method using context parameter " + context.getAttribute("userName"));
	}
```

![](/files/-Lcoszun7Ep2eSh0iW1J)

### Output:

![](/files/-Lcot3pNUoOvXU8YrIlq)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-jspandservlets-for-java.gitbook.io/workspace/request-session-and-context-part-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
