• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

HttpServletRequest

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Stu Johns
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
excellent, thanks.
reply
    Bookmark Topic Watch Topic
  • New Topic