Java HttpServletRequest get cookie

Description

Java HttpServletRequest get cookie

import java.io.IOException;
import java.io.PrintWriter;

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 Main extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
      PrintWriter out = response.getWriter();
      Cookie[] cookies = request.getCookies();
      boolean found = false;
      if (cookies != null)
         for (int i = 0; i < cookies.length; i++)
            if (cookies[i].getName().equals("session_started")) {
               found = true;//from w  w  w  .  j av a  2s . c o m
               out.println("You started this session on : ");
               out.println(cookies[i].getValue());
            }
      if (!found) {
         String dt = (new java.util.Date()).toString();
         response.addCookie(new Cookie("session_started", dt));
         out.println("Welcome to out site...");
      }
   }
}



PreviousNext

Related