Loading

Cookie的一些用法

Cookie的一些用法:

package com.stono.servlet.listenerorder;
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 TestCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("c1", "c1");
        cookie.setMaxAge(30 * 60);
        // 如果设置MaxAge为0,会导致Cookie立刻失效,在第二次访问的时候就已经没有Request Cookie了;
        // cookie.setMaxAge(0);
        // 进行添加之后,在ChromeDeveloperTools中可以看到Response Cookies;进行其他页面的请求,可以看到Request Cookies;
        resp.addCookie(cookie);
        Cookie[] cookies = req.getCookies();
        // 第一次输出1,只有JSESSIONID,第二次输出2,还有c1
        System.out.println(cookies.length);
        PrintWriter writer = resp.getWriter();
        writer.println("com.stono.servlet.listenerorder.TestCookieServlet.doGet(HttpServletRequest, HttpServletResponse)");
    }
}

 

posted @ 2015-10-08 17:23  stono  阅读(124)  评论(0编辑  收藏  举报