Programming Practices – Proper Implementation of Session Variables

programming practicessession

Is there any other reason for using session variables besides keeping the values longer than the current request? For instance, is it advisable to use session data when storing information in a file on the file system to prevent one user from writing data to the file of another user? I understand what a session variable is, but I'm not for sure how to properly implement it.

Best Answer

All web frameworks within the Java/.NET world will let you access the session, and as such to the content related to the connected user. Generally, sessions are implemented as Maps (Java) or Dictionaries (.NET). HTTP is a "stateless" protocol, therefore sessions have been invented on the server side to keep some form of state between two requests. Check out Sun's documentation on designing EE applications, and when to use a given scope (page, request, session, application), more specifically the 4.4.7 paragraph.

From the developer point of view, one of the best practices is to build your own object that will keep all of data related to the user (example: UserData object with id, username, etc.) and map it as a session variable, instead of directly mapping each user's property directly to the session. You can implement a mechanism that saves the session in the database, in a file but you don't have to worry about one user writing into the session of another user, this is not going to happen (unless it has been hacked, and you have a bigger problem at hand).

The session scope keeps data longer than the request scope as you say. However, the request scope is populated with data entered by the user (it is generally possible to "hack" that and add values on the server side, but that's generally a bad design), whereas the session scope can only be populated from the server side. As @KyleHodgson wrote, more than often you use it to keep in there data that you don't want to retrieve from the database each time the same user sends a request. That is why you'll generally find there the user name, the user profile/preferences, the rights of the user, etc. And you update these session data only if the information is updated, for example when the user changes some preferences.