java中session和cookie的创建与销毁

1.后端创建cookie
Cookie cookName =newCookie("cookName", cookValue);
cookName.setMaxAge(60*60*24*7);//设置cookie的最大生命周期为7天
cookName.setPath("/"); //设置路径为全路径(这样写的好处是同项目下的页面都能访问该cookie
response.addCookie(cookName); //response是HttpServletResponse类型
2.后端创建session
HttpSession session = request.getSession(); //request是HttpServletRequest类型的
session.setAttribute("manuse", manuse);//往session中添加字段
session.setAttribute("rank", rank);
3.后端获取cookie并干掉cookie
@CookieValue("cookieName")Cookie cookieName//@CookieValue是spring提供的注解,用在参数里
userCookie.setMaxAge(0);
userCookie.setPath("/"); //路径一定要写上,不然干不掉的
response.addCookie(userCookie);
4.后端获取session并干掉session
HttpSession session = request.getSession();
session.invalidate();
5.前端获取session中某个字段的值
el表达式可直接获取:${ attributeName}

6.前端获取cookie中某个字段的值
<%--jQuery文件 cookie操作插件--%>
< script src= "https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js" > script >
var userName = $ .cookie( 'cookName' );(要写在script标签里)

------------------------------------------------下面是两个例子--------------------------------------------------------
//退出
@RequestMapping("/destroyCookie")
publicString destroyCookie(@CookieValue("cookName") Cookie userCookie,HttpServletResponse response, HttpServletRequest request) {
//干掉cookie
userCookie.setMaxAge(0);
userCookie.setPath("/");
response.addCookie(userCookie);
//干掉session
HttpSession session = request.getSession();
session.invalidate();
return"exitSuccess";
}

//登陆
@RequestMapping("/frames")
publicModelAndView login(@RequestParam("userName") String userName,
@RequestParam("pwd") String pwd, String rank, 
HttpServletResponse response, HttpServletRequest request) {
HttpSession session = request.getSession();
ModelAndView mv =newModelAndView();
//若是员工
if(rank.equals("1")) {
Staff s =newStaff(userName, pwd);
Staff staff = entityService.selectStaff(s);
if(staff ==null) {
mv.setViewName("redirect:/jump/false");
returnmv;
}
session.setAttribute("nowUserId", staff.getId());
}
//若是管理员
else{
Manager manager1 =newManager(userName, pwd);
Manager manager = entityService.selectManager(manager1);
if(manager ==null) {
mv.setViewName("redirect:/jump/false");
returnmv;
}
}
//创建cookie传入用户
Cookie cookName =newCookie("cookName", userName);
cookName.setMaxAge(60*60*24*7);
cookName.setPath("/");
response.addCookie(cookName);

Manuse manuse =entityService.selectManuse();
//往session传值
session.setAttribute("manuse", manuse);
session.setAttribute("rank", rank);
mv.setViewName("frames");
returnmv;
}

你可能感兴趣的:(java中session和cookie的创建与销毁)