Friday, February 10, 2012

java - Cookies

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

public class CookieExample extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // print out cookies

        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            String name = c.getName();
            String value = c.getValue();
            out.println(name + " = " + value);
        }

        // set a cookie

        String name = request.getParamter("cookieName");
        if (name != null && name.length() > 0) {
            String value = req.getParameter("cookieValue");
            Cookie c = new Cookie(name, value);
            res.addCookie(c);
        }
    }
}

No comments: