Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for use of session and request attributes in servlet and JSP for MVC compliance

I have a scenario where a servlet is required to display details of a person on a page, but I want to also store the details of the person in the session, so is this code viable:

Person person = // Populated elsewhere.   
session.setAttribute("person", person); // Store Person in session.
request.setAttribute("person", person); // Store Person in request.
// Set URL for JSP.

I ask because the session object can be accessed by the JSP. Or is it better to populate the JSP only using the request because this is more MVC compliant?

like image 507
Mr Morgan Avatar asked Dec 31 '25 05:12

Mr Morgan


1 Answers

It depends on your code. If you need to store that information permanently within the session, store it in session. So all JSPs can access this data.

If you need to store that information but only for request purposes (such as Forms), store it in request. So only the JSP to which you forward the request can read the data.

like image 83
Matteo Pampana Avatar answered Jan 03 '26 14:01

Matteo Pampana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!