Cookie,session

Cookie是服务器通知客户端保存键值对的一种技术。
客户端有了Cookie后,每次请求都会发送给服务器。
Cookie 的值可以唯一地标识客户端,因此 Cookie 常用于会话管理。
每个Cookie的 大小不能超过4kb。

1.创建Cookie

1
2
3
4
5
6
7
8
9
public class CookieServlet extends BaseServlet {
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.创建Cookie对象
Cookie cookie = new Cookie("key1", "value");
// 2.通知客户端保存Cookie
resp.addCookie(cookie);
resp.getWriter().write("Cookie创建成功");
}
}

2.服务器获取Cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for(Cookie cookie:cookies){
// getName()返回cookie的key
// getValue()返回cookie的value
resp.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]<br/>");
}
Cookie iwantCookie = null;
/*for(Cookie cookie:cookies){
// 给到想要的cookie
if("key1".equals(cookie.getName())){
iwantCookie = cookie;
break;
}
}*/
iwantCookie = CookieUtils.findCookie("key1",req.getCookies()); if(iwantCookie!=null){
resp.getWriter().write("找到了指定的cookie");
}
}

将查找指定Cookie封装成工具类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package Utils;

public class CookieUtils {
/**
* 查找指定名称的cookie
* @param name
* @param cookies
* @return cookie
*/
public static Cookie findCookie(String name,Cookie[] cookies){
if(name==null||cookies==null||cookies.length==0){
return null;
}
for(Cookie cookie:cookies){
// 给到想要的cookie
if(name.equals(cookie.getName())){
return cookie;
}
}
return null;
}
}

3.Cookie值的修改

方案一:
1、先创建一个要修改的同名(指的就是key)的Cookie 对象
2、在构造器,同时赋于新的Cookie 值。
3、调用response.addCookie( Cookie );

方案二:
1、先查找到需要修改的Cookie 对象
2、调用setValue()方法赋于新的Cookie 值。
3、调用response.addCookie()通知客户端保存修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/* // 方式一:
// 1、先创建一个要修改的同名(指的就是key)的Cookie 对象
// 2、在构造器,同时赋于新的Cookie 值。
Cookie cookie = new Cookie("key1", "value2");
// 3、调用response.addCookie( Cookie );通知客户端保存cookie
resp.addCookie(cookie);
*/

// 方式二:
// 1、先查找到需要修改的Cookie 对象
Cookie cookie = CookieUtils.findCookie("key1",req.getCookies());
// 2、调用setValue()方法赋于新的Cookie 值。
if(cookie!=null){
cookie.setValue("value3");
}
// 3、调用response.addCookie()通知客户端保存修改
resp.addCookie(cookie);
}

4.Cookie的生命控制

管理cookie什么时候被销毁(删除)
setAge():
正数表示在指定的秒数后过期;
负数表示浏览器关闭后,cookie就会销毁;()默认值为-1
0表示马上删除cookie。

1
2
3
4
5
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defaultLife","defaultLife");
cookie.setMaxAge(-1); // 设置存活时间
resp.addCookie(cookie);
}
1
2
3
4
5
6
7
8
protected void deleteCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("defaultLife",req.getCookies());
if(cookie!=null){
cookie.setMaxAge(0);// 马上删除cookie
resp.addCookie(cookie);
resp.getWriter().write("cookie[defaultLife=defaultValue]已删除");
}
}

5.Cookie有效路径Path的设置

Cookie的path属性可以有效的过滤哪些Cookie可以发送 个服务器。
path属性是通过请求的地址来进行有效的过滤。

1
2
3
4
5
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key2","value2");
cookie.setPath(req.getContextPath()+"/a"); // 设置Path值为 /工程路径/a
resp.addCookie(cookie);
}

6.免输入用户名登录

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form action="http://localhost:8080/08_cookie/loginServlet" method="post">
用户名:<input type="text" name="username" value="${cookie.username.value}"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
if("zyz".equals(username)&&"123456".equals(password)){
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(60*60*24*7);// cookie一周内有效
resp.addCookie(cookie);
System.out.println("登录成功!");
}else{
System.out.println("登录失败!");
}
}
}

Session

1、Session 是一个接口(HttpSession)。
2、Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个Session 会话。
4、Session 会话中,我们经常用来保存用户登录之后的信息。

1.创建和获取session

request.getSeesion():
第一次调用:创建Session会话。
之后的调用:获取前面创建好的Session会话对象。
isNew():判断Session是否是刚创建的
    true:表示刚创建
    false:表示获取之前创建
getId():得到Session的会话id值

1
2
3
4
5
6
7
8
9
10
11
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建或获取Session会话对象
HttpSession session = req.getSession();
// 判断Session是否是刚刚创建的
boolean isNew = session.isNew();
// 获取Session会话的唯一标识id
String id = session.getId();

resp.getWriter().write("得到Session,id为:"+id+"<br/>");
resp.getWriter().write("是否是刚刚创建的:"+isNew+"<br/>");
}

2.Session域数据的存取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 往Session域中保存数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1","value1");

}

/**
* 获取Session中的数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object key1 = req.getSession().getAttribute("key1");
resp.getWriter().write("从Session中获取的key1的数据为:"+ key1);
}

3.Session生命周期控制

setMaxInactiveInterval(int interval):设置Session超时时间,超过指定的时长就会被销毁。
负数表示永不超时。
getMaxInactiveInterval():获取Session超时时长。
invalidate():使当前会话马上超时。

获取默认超时时长:

1
2
3
4
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session的默认超时时长为:"+maxInactiveInterval);// 1800
}

设置web工程下所有的 Session 默认超时时长:

1
2
3
<session-config>
<session-timeout>20</session-timeout>
</session-config>

设置个别Session的超时时长:

1
2
3
4
protected void setLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setMaxInactiveInterval(3);
resp.getWriter().write("设置Session 3秒后失效~");
}

使Session马上失效:

1
2
3
4
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().invalidate();
resp.getWriter().write("设置Session 马上失效~");
}