Billie
Billie

Reputation: 9146

corresponding jsp `session` variable in servlet?

In JSP we have the session variable. What is the corresponding variable in servlet?

Tried request.getSession() but it the request session. I want the global session

Upvotes: 0

Views: 276

Answers (2)

Vladimir
Vladimir

Reputation: 1694

You must understand different scopes. A “scope” is a place that the bean is stored. This place controls where and for how long the bean is visible.

There are three choices:

  1. Request scope • Data stored in the request is visible to the servlet and to the page the servlet forwards to. Data cannot be seen by other users or on other pages. Most common scope.

  2. Session scope • Data stored in the request is visible to the servlet and to the page the servlet forwards to. Data can be seen on other pages or later in time if it is the same user. Data cannot be seen by other users. Moderately common.

  3. Application scope(Servlet Context) • Data stored in the servlet context is visible to all users and all pages in the application. Rarely used.

JSP session, 'sessionScope' object in servlet is used like this:

HttpSession session = request.getSession();
session.setAttribute("key", value);

Request scope use:

request.setAttribute("key", value);

Application (Servlet context) scope use:

getServletContext().setAttribute("key", value);

[source: all about servlets and JSP and much more: http://www.coreservlets.com/]

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

The session implicit variable that you have in the JSP is the same thing as request.getSession(). There is no such thing as a "global" session. Each request comes with a cookie which identifies the session it "belongs" to. That's why you need a request to get the session.

Upvotes: 2

Related Questions