wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "HttpServletRequest" Watch "HttpServletRequest" New topic
Author

HttpServletRequest

Stu Johns
Ranch Hand

Joined: Aug 11, 2008
Posts: 63
Hi
I'm pretty new to the servlets and I'm wondering what is the difference between using:
HttpServletRequest.getSession().setAttribute()
and
HttpServletRequest.setAttribute()
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
Thanks

Stu.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41180
    
  45
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.


Ping & DNS - my free Android networking tools app
nans nav
Greenhorn

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: http://aspose.com/file-tools
 
subject: HttpServletRequest
 
Similar Threads
accessing a session attribute from a class that implements Filter
New session id in Jboss
HttpServletRequest getSession methods
Different ways to access the application’s ServletContext object in a servlet
Session Timeout