4.session :会``话
a.浏览网站:开始-关闭
b.购物: 浏览、付款、退出
c.电子邮件:浏览、写邮件、退出
以上这些开始-结束都是一次会话
Session机制:
客户端第一次请求服务端时,服务端会产生一个session对象(用于保存该客户的信息);
并且每个session对象,都会有唯一的sessionId(用于区分其他session);
服务端又会产生一个cookie,并且该cookie的name=JSESSIONID,value=服务端的sessionId 的值。
然后服务端的session与客户端的cookie一一对应。
sessionId 与JSESSIONID
客户端第二次请求时,会直接用上次产生的session
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name=request.getParameter("uname");
String pwd=request.getParameter("upwd");
if(name.equals("zmx")&&pwd.equals("123")){
//验证用户名密码的匹配然后添加session属性
session.setAttribute("uname",name);
session.setAttribute("upwd",pwd);
session.setMaxInactiveInterval(10);//session最大有效时间是10秒
request.getRequestDispatcher("welcome.jsp").forward(request, response);//转发
}
else{
//失败就返回登录界面
response.sendRedirect("login.jsp");//重定向
}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
welcome!!!
<%
String name=(String)session.getAttribute("uname");//object对象转为String
if(name!=null){
out.print(name);
}
else{
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%=session.getAttribute("uname")//同一次会话,不用登录都可以得到了。
%>
</body>
</html>