Persisting state in Servlets

Only a single instance of the servlet is created, and each request simply results in a new thread calling the servlet’s service method (which calls doGet or doPost). So, shared data simply has to be placed in a regular instance variable (field) of the servlet. Thus, the servlet can access the appropriate ongoing calculation when the browser reloads the page and can keep a list of the N most recently requested results, returning them immediately if a new request specifies
the same parameters as a recent one. Of course, the normal rules that require authors to synchronize multithreaded access to shared data still apply to servlets.

Servlets can also store persistent data in the Servlet-Context object that is available through the getServletContext method. ServletContext has setAttribute and getAttribute methods that let you store arbitrary data associated with specified keys.

The difference between storing data in instance variables and storing it in the Servlet- Context is that the ServletContext is shared by all servlets in the servlet engine.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: