request.setAttribute and request.getSession().setAttribute()

12,463

Difference :

When you use request.setAttribute, you store something for the same request object. You can use this attribute later on when you do a forward from your current servlet/jsp to some other servlet/jsp.

When you use request.getSession().setAttribute(), you store something for that particular user session. You can use this attribute whenever you want if the user session has not expired.

Where are they stored and in which format :

The servlet container will manage where to store the values. And the values are always stored as String.

An example :

Let's say that there is an html page for entering student marks which is sent to some servlet X and you want to use those values in servlet Y. So you set the mark values in the servlet X request attribute and then forward to servlet Y and use those variables.

But let's say that you have multiple ui pages and when the user logs out you want to alert him with his name. So what you can do is, to store his name in request.getSession().setAttribute() and in your logout page, you can get the value stored in session for the alert.

Share:
12,463
Aravind Ram
Author by

Aravind Ram

Updated on June 04, 2022

Comments

  • Aravind Ram
    Aravind Ram almost 2 years

    What is the difference between request.setAttribute and request.getSession().setAttribute() ?
    Where are they stored and in which format?

  • Aravind Ram
    Aravind Ram about 9 years
    thanks :) but where will they get stored and in which format??
  • Aravind Ram
    Aravind Ram about 9 years
    Does request.setAttribute() method store the attributes as a part of request body or will they be stored in the server?
  • Abubakkar
    Abubakkar about 9 years
    it should be stored as part of request object.