File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Spring in Action this week in the Spring 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: 42274
    
  64
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: HttpServletRequest