April 10, 2011

Set a Cookie in a Servlet

1) Create the CookieDemo.java Servlet class with code to set a cookie header in the response

package info.icontraining.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieDemo extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      Cookie cookie = new Cookie("cookiedemo","cookievalue");
      response.addCookie(cookie);
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      out.println("Sending response with Cookie<br/>");
      out.println("<a href=\"cookieDemo2\">Click Link</a>");
   }
}


2) Create the CookieDemo2.java Servlet class with code to retrieve from the request that was set/sent in the previous Servlet.

import javax.servlet.http.*;
import java.io.*;

public class CookieDemo2 extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      Cookie[] cookies = request.getCookies();
  
      for (Cookie c: cookies) {
         out.println("Cookie Name is " + c.getName() + "<br/>");
         out.println("Cookie Value is " + c.getValue() + "<br/><br/>");
      }

      response.setContentType("text/html");
   }
}


3) Configure both servlets in the web.xml

<servlet>
   <servlet-name>CookieDemo</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo</servlet-name>
   <url-pattern>/cookieDemo</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>CookieDemo2</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo2</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo2</servlet-name>
   <url-pattern>/cookieDemo2</url-pattern>
</servlet-mapping>


4) Test the code with the following URL in the browser

http://localhost:8080/WebAppName/cookieDemo

No comments:

Post a Comment