Thursday, December 1, 2011

ServletContext

Using a static class variable like we did (nextUserId) in a Servlet is not such a good idea - it is known to have some issues in multi-threading, and also because the exact lifecycle of a Servlet is controlled by the Servlet container.

So it is recommended to use ServletContext.

ServletContext is a global object which is created when the Application is started and exists until the Application is shut down (this is called 'Application-Scope').

Any Servlet can access the ServletContext object by calling getServletContext()

Here is our HelloWorld again, this time using ServletContext:

 package org.confucius;   

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet{

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String cookieValue = getCookieValue(request.getCookies(), "userId");

if (cookieValue == null){
ServletContext context = getServletContext();
Integer nextUserId = (Integer) context.getAttribute("nextUserId");

if (nextUserId == null){
nextUserId = new Integer(0);
context.setAttribute("nextUserId", nextUserId);
}

Cookie userCookie = new Cookie("userId", nextUserId.toString());
response.addCookie(userCookie);
nextUserId++;
context.setAttribute("nextUserId", nextUserId);
}

response.getWriter().write("User ID = " + cookieValue);
}

private String getCookieValue(Cookie[] cookies, String cookieName) {
if (cookies == null)
return null;

for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return (cookie.getValue());
}
return null;
}
}

No comments: