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:
Post a Comment