1.会话
会话:用户打开一个浏览器,点击了很多超链接,访问了多个web资源,随后关闭浏览器,这个过程则称之为会话;
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学曾经来过,称之为有状态会话;
保存会话状态的两种技术:1.cookie 2.session
什么是session?什么是cookie?session和cookie有什么区别?
2.Cookie应用
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//从客户端请求中获取cookie数组
Cookie[] cookies = req.getCookies();
if(cookies == null){
out.print("cookie为空");
}else
{
//cookie数组不为空,则遍历数组,从数组中寻找符合要求的cookie
for(Cookie cookie:cookies) {
if(cookie.getName().equals("name")){
out.print("name: " + cookie.getValue());
return;
}else {
//找不到符合要求的cookie则代表用户视第一次登陆该网站
out.print("这是您第一次登陆该网站");
}
}
}
//新增cookie,并通过HttpServletResponse对象发送给客户端
Cookie cookie = new Cookie("name","xld");
resp.addCookie(cookie);
out.close();
}
}
3.Session应用
ublic class SetSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//创建Session对象
//如果请求中没有携带SessionId,那么服务器就会创建一个新的session对象,并返回一个sessionId
//如果请求中携带了SessionId,那么服务器跟根据SessionId从散列表中找到对应的session对象
HttpSession httpSession = req.getSession();
//在session里面设置值
httpSession.setAttribute("name","xld");
//获得session的id
String id = httpSession.getId();
if(httpSession.isNew()){
out.print("session创建成功,id: " + id);
}else{
out.print("session已经存在了,id: " + id);
}
}
}
public class GetSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//创建Session对象
HttpSession httpSession = req.getSession();
//获得session对象中的值
String value = httpSession.getAttribute("name").toString();
out.print("session的值为:" + value);
}
}
注:session信息是存放在服务器端的,客户端访问服务器端时,只要客户端不关闭(即不关闭浏览器),那么其对应的session对象就会服务器端一直存在服务器端的内存中。