Posted in Software Engineering, Technology
Monday, March 20, 2006
One of the lovely things about the Web is that you can traverse pages in any order you like. Sometimes it is necessary to remember information between pages. Think about Amazon.com’s shopping cart. As you find items you like, you can add them to the shopping cart. When you are ready to check out, the items selected are displayed. In order to remember information as you navigate between pages, a web application has to maintain ‘state’. In computer geek terms we say that the shopping cart application is stateful.
In order to remember your shopping cart items the application uses a server provided construct called a session. A session persists for a specified period of time across multiple connections and page requests from the same client. Using the session and a database we can store, retrieve and associate session data with a given user ID.
One mistake to maintain state is to use hidden form fields. This is a security risk open to an exploit known as cross-site scripting. It is much better to store such values on a database instead. You can use the session id as a key field. On subsequent pages the value can be looked up.
Another mistake is to try to maintain state by trying to persist data in objects declared in servlet code. This breaks down when there are multiple users. These objects are not thread-safe. That is, one user’s data can corrupt another user’s data.
So a good way to implement state in a web application is to use a database in conjunction with the session. By avoiding some common mistakes you can protect your website.
