状态管理
记录同一用户的网络连接的数据,避免每次都重新建立网络连接。
Cookie-客户端
服务器set-Cookie并以消息头方式发送给客户端(浏览器),然后浏览器保存cookie
- 服务器创建
Cookie cookie = new Cookie("name","just");
response.addCookie(cookie);
- 客户端查询和修改
<%
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
//修改
cookie.setValue("newjust");
response.addCookie(cookie);
}
}
%>
Cookie生存时间
- setMaxAge(seconds)生存时间
- seconds>0 浏览器根据seconds时间删除cookie,浏览器将cookie保存至硬盘
- seconds=0 reponse后,即删除
- seconds<0 默认,浏览器将cookie保存至内存
Cookie中文处理
//设置
cookie = new Cookie("city", URLEncoder.encode("北京","utf-8"));
//获取
value = URLDecoder.decode(value, "utf-8");
Cookie路径
默认路径:web应用路径+response目标路径 /appPath/xx/response.jsp
若已经保存当前cookie,访问其他页面,只有为 /appPath/xx路径或其子路径才会发送cookie
设置路径:
//如,项目根路径
cookie.setPath(request.getContextPath());
Cookie不足
- 用户可禁止
- 不安全,需要加密
- 只能保存少量
- 个数有限
- 只能保存字符串
Session-服务器端
服务器为每一个浏览器在内存中分配空间,单独创建一个Session对象,对象sessionId值唯一。当浏览器再次访问服务器,会将sessionId发送给服务器,服务器则根据sessionId获取Session。
Session常用于保存用户登录信息
Session操作
获取
HttpSession httpSession = request.getSession(true);
参数:
- 默认为true,若session存在则直接返回,若session不存在则创建后返回
- 为false,则session存在返回,不存在返回null
绑定对象
httpSession.setAttribute("count",count); //绑定
httpSession.getAttribute("count"); //获取
httpSession.removeAttribute("count"); //移除
移除Sesssion
httpSession.invalidate();
生命周期
默认当浏览器关闭时,session失效,但某些业务肯定需要限制Session存在时间
方法:
- 1, tomcat目录 /conf/server.xml
<session-config>
<session-timeout>30</session-timeout> //分钟
</session-config>
- 2, 代码
httpSession.setMaxInactiveInterval(30*60); //秒
示例:
同一Session中,记录访问次数
- java
public class SessionServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8"); //编码
PrintWriter out = resp.getWriter();
HttpSession httpSession = req.getSession(); //获取session
httpSession.setMaxInactiveInterval(30*60); //设置存在时间
String type = req.getParameter("type");
if("logout".equalsIgnoreCase(type)){
//模拟退出登录删除session
if(httpSession!=null) {
httpSession.invalidate();
}
out.println("已退出登录!");
//若之前是登录状态,则可以看到RequestHeader中sessionId与 ResponseHeader中sessionId 是不同的
out.println("sessionId:"+httpSession.getId());
out.println("<br/>");
out.close();
}else{//模拟访问
Integer count = (Integer) httpSession.getAttribute("count");
if (count == null) {
count=1;
}else{
count++;
}
httpSession.setAttribute("count",count);
// httpSession.getAttribute("count");
// httpSession.removeAttribute("count");
out.println("第"+count+"次访问!");
out.println("<br/>");
out.println("SessionId:"+httpSession.getId());
out.close();
}
}
}
- web.xml
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>com.core.just.filter.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/count/*</url-pattern>
</servlet-mapping>
- 浏览器查看
若第一次访问服务或退出登录后再次访问,那么在Response Headers中会有JSESSIONID:
Set-Cookie:JSESSIONID=B62E1EBA6241D90352F8465553C1F68A; Path=/; HttpOnly
若用户Session还生效的情况下,访问服务,那么在Request Headers中会有JESSIONID:
Cookie:Idea-81111fc3=bf89d114-df52-4038-bf56-d69e0305fad9; JSESSIONID=26A67EB967DD4B525FDBA972D6E0D6C1
如果用户将浏览器Cookie禁用怎么办?
用户禁用Cookie那么服务器就无法将Cookie和Session发送给浏览器
解决:重写URL
//重定向
resp.sendRedirect(resp.encodeRedirectURL("url"));
//表单和链接地址
resp.encodeURL("url")
Session 特点
- 安全,数据保存在服务端
- 类型更多,Object类型
- 数据更多,依靠服务器性能
JSESSIONID
- session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我们叫做session cookie,以区别persistent cookies,也就是我们通常所说的cookie;
- session cookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid