File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes HttpServletRequest Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "HttpServletRequest" Watch "HttpServletRequest" New topic


Stu Johns
Ranch Hand

Joined: Aug 11, 2008
Posts: 63
I'm pretty new to the servlets and I'm wondering what is the difference between using:
I have read the javadoc that getSession will create a session if theres not one, but i dont understand why a session is not there if I have a HttpServletRequest object and hence the use of the getSession method.
Any advice appriciated

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Two things here. Firstly, the two statements do different things. The former creates a session attribute, while the latter creates a request attribute. The difference is that session attributes live as long as the session lives, so the second page request of the same user has access to session attributes that were set during the first page request. Request attributes, on the other hand, only live for the duration of the current request; once the response is sent back to the browser, they're gone.

As to your second question, sessions are optional. Not every web app uses them, or wants to use them. It makes sense to only create them if the web app code explicitly asks for them.
nans nav

Joined: Jun 07, 2007
Posts: 8
HttpServletRequest.getSession().setAttribute() sets an attribute in session scope, while HttpServletRequest.setAttribute() sets the attribute in request scope.
If an attribute is set using the first it will be available for the whole session across the multiple requests. For the second it will be available only for a given request.

For more understanding, read the difference between request and session.

SCJP 5.0<br />SCWCD 5.0
Stu Johns
Ranch Hand

Joined: Aug 11, 2008
Posts: 63
excellent, thanks.
I agree. Here's the link:
subject: HttpServletRequest
It's not a secret anymore!