学习——JavaWeb07:cookie与session
学习——JavaWeb07:cookie与session
Ø 1.Cookie
1、 服务端准备cookie;
Response.addCookie(Cookie cookie)
2、 页面跳转(转发、重定向)
客户端获取cookie:request.getCookies();
1、 不能直接获取某一个单独对象,只能一次性将全部的cookie拿到
2、 服务端增加cookie:response对象;客户端获取cookie:request;
通过F12可以发现,除了自己设置的cookie之外,还有一个key为JSESSIONID的cookie
建议cookie只保存英文数字,如果用到中文,则需要进行编码、解码。
2.Cookie实现 记住用户名功能
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
String name;
String password;
%>
<%
Cookie[] cookies = request.getCookies();
boolean flag = false;
for(Cookie cookie:cookies){
if(cookie.getName().equals("name")){
name=cookie.getValue();
flag=true;
}
if(cookie.getName().equals("pwd")){
password=cookie.getValue();
}
}
if(!flag){
out.print("cookie已失效!");
}
else{
out.print("cookie:"+name);
}
%>
<form action="check.jsp" method="post">
用户名:<input type="text" name="name" value="<%=(name==null?"":name)%>"/><br>
密码:<input type="password" name="password" value="<%=password==null?"":password%>"/><br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("password");
//将用户名加入到cookie中
Cookie cookie1 = new Cookie("name",name);
Cookie cookie2 = new Cookie("pwd",pwd);
cookie1.setMaxAge(10);
cookie2.setMaxAge(10);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.sendRedirect("A.jsp");
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.print("成功!!!<br/>");
%>
</body>
</html>
3.session(会话对象)
1.浏览网站:从开始到关闭被称为一次会话;
2.购物: 浏览——>写邮件——>退出;
3.电子邮件: 浏览——>写邮件——>退出;
Session机制;
客户端第一次请求服务器端时:
会先去本地查找jsessionId与服务端匹配(结果失败)
服务端会产生一个session对象(用于保存该客户的信息);
并且每个session对象 都会有一个自带的唯一sessionId (为了区分于其他的session);
服务端又会产生一个cookie,并且 该cookie的name和value都写死了:JSESSIONID,sessionId.
然后 服务端会在响应客户端的同时将该cookie发送给客户端,致此,客户端就有了一个cookie,并且里面有一个JSESSIONID了;
因此:客户端的cookie就可以和服务端的session一一对应(JSESSIONID-sessionID)
第二次请求时:
服务器会先根据用户客户端的cookie中的JSESSIONID去服务端session中匹配,
如果匹配成功,说明此用户不是第一次访问,所以不需要再次登录