Session Tracking
HTTP is stateless protocol i.e. it does not remember its previous state.
<input type ="hidden" name = "name" value="">
<a href = "MyServlet"?p=1> Click1 </a> <a href = "MyServlet"?p=2> Click2 </a>This value "p" can be read in the servlet as request.getParameter ("p");
Server generates a unique
session id and sends it as a cookie to the browser.
request.getSession() : When we call this inside a servlet, a session is automatically created by the servlet container (i.e. Tomcat) and a unique session id is sent to the client. This ID is always communicated back by the client to keep the session alive.
The ServletContext, HttpSession, and HttpRequest objects in the Servlet specification are referred to as scoped containers. Each of these has getAttribute() and setAttribute() methods, which store data on behalf of the application. The difference between them is the lifetime of the scoped container. For HttpRequest, the data only persists for the lifetime of the request; for HttpSession, it persists for the lifetime of a session between a user and the application; and for ServletContext, it persists for the lifetime of the application.
Servlet-Instance-Sharing : By default, the servlet engine loads only a single instance of a servlet. Requests serviced by the servlet are run in separate threads, but share the same instance and, therefore, the same instance variables.
Example //The following code is bad from a multi-threading perspective public class ColliderServlet extends HttpServlet { private Connection con; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:usda"); // ... run some lengthy database operation here } catch (Exception e) { throw new ServletException(e.getMessage()); } } } Two threads accessing the method service will create two objects of con and since there is only one instance of this class, the older con will be overwritten by newer con. Hence the thread that enters before will have some junk con object and will crash.
Although the single instance multiple thread model is the default, a servlet can change this behavior by implementing SingleThreadModel. This interface, which has no methods, informs the servlet engine that it should create a pool of instances and allocate each incoming request to its own instance and thread. This guarantees no two requests handled by the same instance will overlap in their execution of the service method. Thus, instance variables can only be affected by one request at a time, making them thread safe. |
Got a thought to share or found a
bug in the code?
We'd love to hear from you:
Name: | |
Email: | (Your email is not shared with anybody) |
Comment: |
Facebook comments: