Cookie ,Session的基本用法

来源:互联网 发布:java 开源框架 编辑:程序博客网 时间:2024/06/07 23:46

<%@ 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>
<!-- 写Cookie -->
<%
Cookie cookie=new Cookie("cookieName","hello !!");
cookie.setMaxAge(2*60);
response.addCookie(cookie);
cookie=new Cookie("cookie","hello !!");
cookie.setMaxAge(2*60);
response.addCookie(cookie);
%>
<!-- 获取客户端的cookie -->
<%
Cookie[] cookies=request.getCookies();
if(cookies!=null){
  for(Cookie c:cookies){
   String name=c.getName();
   String value=c.getValue();
  }
}

%>
需要写Cookie:登录成功以后、浏览过商品以后、选择对比功能以后
读取Cookie:在进入登录页面以前、在浏览商品页面时

<!-- 用户权限管理 -->
在用户登录成功后,向session中添加一个数据
<%
session.setAttribute("login", "success");
%>
在其他页面获取session中的数据,
<%
String info=(String)session.getAttribute("login");
if(info==null||"success".equals(info)==false){
  response.sendRedirect("login.jsp");
}
%>
<!-- 移除session中的数据 -->
<%
session.removeAttribute("info");
%>
<%
session.invalidate();
%>


</body>
</html>