Request, Session and Context Part -1

Lets try to answer the below problems:

1) What are request and response objects ?

2) Is servlet itself an object ?

3) When are these objects are created and destroyed ?

1) Request and response objects are created per access by the tomcat every time when the request is fired .

2) Servlet object is also created by tomcat but not per access.

3) Different requests have different servlet thread , not instances for better performance.

Http - a stateless protocol (Connection less)

For 1 request : (new Request object is created with pathvariable as userName = Mohit)

For 2 request : (new Request object is created with pathvariable null )

Session Object:

How to remember ? if http is stateless.

Use Session object from request object.

When query parameter is passed :

When query parameter is not passed :

Username mohit is still coming from session object.

Code snippet :

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Hello from Get method of XML servlet");
		response.setContentType("text/html");
		String userName = request.getParameter("userName");
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Hello from GET method using request parameter " + userName);
		HttpSession httpSession = request.getSession();
		if (userName != null) {
			httpSession.setAttribute("userName", userName);
		}
		printWriter.println("Hello from GET method using session parameter " + httpSession.getAttribute("userName"));
}

Last updated

Was this helpful?