xiongxin / Blog

xiongxin's blog base on issues
0 stars 0 forks source link

Serverl学习笔记一 Cookie和Session #2

Open xiongxin opened 8 years ago

xiongxin commented 8 years ago

Cookie和Session

Cookie

Cookie myCookie = new Cookie("username", myName);
//设置Cookie的过期时间
myCookie.setMaxAge(1999); //单位秒
//发送Cookie到客户端
resp.addCookie(myCookie)
Cookie[] cookies = request.getCookies();
if (cookies !=null) {
    for (Cookie cookie:cookies) {
        if(cookie.getName.equals("userName") ) { //是否存在一个userName的Cookie
             value = cokkie.getValue("userName")  //存在的话就读取里面的值
        }
    }
}

Session

HttpSession session = req.getSession();
session.setAttribute("username", myName);

//过期时间
session.setMax...(20);//单位分钟
session.invaliate()//session失效
String name = (string) session.getAttrbute("username");
if (name !=null) {
    System.out.println(name);
}