Servlets: setAttribute in HttpServletRequest vs setAttribute in HttpSession

What is the difference between the setAttribute() method of the HttpServletRequest class and setAttribute() of the HttpSession class?

Under what circumstances are they used?

+10
source share
3 answers

The attribute sets the attribute in the request area, and the other sets the attribute in the session area. The main difference is the service life. The request area ends when the corresponding response is completed. A session expires when a session has been disconnected by a client or server. When the scope ends, all of its attributes will be broken and they will not be available in another request or session.

You use the request area to store data that should be specific to the HTTP request (for example, database results based on a specific request, success / error messages, etc.). You use a session area to store data that should be specific to an HTTP session (for example, the user on the system, user settings, etc.). All requests from the same client use the same session (thus, all different browser tabs / windows in the same client session will share the same server session).

See also:

+19
source

if you use httpServletRequest.setAttribute (); then the attribute will be bound to this request object,

and in httpServletSession.setAttribute(); attr will be attached. in session.

therefore, if you want the data region of this data to be used in a session , or if you need this region of data for a request only, use request

Example:

The username of the logged in user must be shared by the session, so save it to session

while, the error message that you give the user when considering the authentication error case, it is necessary for this request, only after that we do not need it, so keep it in request

+2
source

When you set the attribute of the Request object, the variable is available only in the request area. This variable can be accessed by other jsp / resources that you submit as part of this request.

When you set the attribute in the session area, all requests in the user's session will be available (unless you delete it from the session).

So the main difference that it compresses is the scope / expiration of the attribute.

Always try to use query scope variables unless you need to use it during an ex: user session as user roles. Saving more data in a session with more concurrent users can lead to memory problems. Also, if you use session sharing supported by a database (for example, you can do it in websphere), this will lead to performance problems.

+2
source

All Articles