Sponsered Links
Categories
Sponsered Links

Servlet Cookies Example

 

This example illustrates how to find cookies value in servlet.

import java.io.*;
import java.util.Random;
import javax.servlet.http.*;
import javax.servlet.ServletException;

public class CookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] coki = request.getCookies();
        Cookie tokens = null;
        if(coki !=null) {
            for(int i=0; i<coki.length; i++) {
                if (coki[i].getName().equals("token")) {
                    tokens = coki[i];
                    break;
                }
            }
        }
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.println("<html><head><title>Tokens</title></head><body ");
        pw.println("style=\"fonr-family:verdana;font-size:10pt\">");
        String reset = request.getParameter("reset");
        if(tokens==null || (reset != null && reset.equals("yes"))) {
            Random rnd = new Random();
            long id = rnd.nextLong();
            pw.println("<p>Welcome. A new token " + id + " is now established</p>");
            tokens = new Cookie("token", Long.toString(id));
            tokens.setComment("Token to identity user");
            tokens.setMaxAge(-1);
            tokens.setPath("/cookie/track");
            response.addCookie(tokens);
        } else {
            pw.println("Welcome back.. Your token is " +    tokens.getValue() + ".</p>");
        }
        String requestURLSame = request.getRequestURL().toString();
        String requestURLNew = request.getRequestURL() + "?reset = yes";
        pw.println("<p>Click <a href=" + requestURLSame +" > here </a> again to continue browsing with the "+ " same identify.</p>");
        pw.println("<p>Otherwise, click <a href = " + requestURLNew + "> here</a> again to start browsing with a new identify. </p>");
        pw.println("</body></html>");
        pw.close();
    }
}

 
 
Sponsered Links
Latest Updates
 
All Content of this site is for learning only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright © 2009 JSPSERVLETTUTORIAL.INFO All Right Reserved