会话技术用户打开一个浏览器访问页面,访问网站的很多页面,访问完成后将浏览器关闭的过程称为是一次会话.
常用会话技术 - Cookie :将数据保存到客户端浏览器.
- Session :将数据保存到服务器端.
为什么使用
私有的数据,信息数据保存在会话技术中. Cookie创建Cookie - Cookie(String name,String value)
常见API - String getName():获取Cookie名
- String getValue:获取Cookie值
- setDomain(String domain):设置Cookie的有效域名
- setPath(String path):设置Cookie的有效路径
- setMaxAge(int maxAge):设置Cookie的有效时间
HttPServletResponse方法 - void addCookie(Cookie cookie):向响应中添加Cookie
HttpServletRequest方法 - Cookie[] getCookies():从请求中取出Cookie
注意:cookie不能存取中文,不可跨浏览器存储 Cookie分类- 会话级别的Cookie:默认的Cookie随着浏览器的关闭而销毁
- 持久级别的Cookie:设置Cookie的有效时间。关闭浏览器Cookie仍会存在
public class CountServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int count = this.getServletContext().getAttribute("count"); count++ this.getServletContext().setAttribute("count",count); response.setContentType("text/html;charset=utf-8"); Cookie[] cookies = request.getCookies(); Cookie cookie = findCookie(cookie,"lastVisit"); if(cookie == null){ response.getWrite().println("<h3>欢迎您第1次登录</h3>"); }else{ Long l =Long.parseLong(cookie.getValue()); Data d = new Date(); response.getWriter.println("您是第"+count+"成功登录的访客!上次访问的时间是:"+d.toLocaleString()); } Cookie c = new Cookie("lastVisit",""+System.currentTimeMillis()); respons.addCookie(c); } private static Cookie findCooikie(Cookie[] cookies,String name){ if(Cookie[] == null){ return null; } for(Cookie cookie:cookies){ if(cookie.getName().equals(name){ return cookie; } } return null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }产品浏览记录 public class CountServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParamter("id"); Cookie[] cookies = request.getCookies(); Cookie cookie = findCookie(cookies,"history"); if(cookie == null){ Cookie c = new Cookie("history",id); c.setPath("/path"); c.setMaxAge(60*60*24); response.addCookie(c); }else{ String[] values = cookie.getValue().split("-"); LinkedList<String> list = new LinkedList<String>(Arrays.asList(values)); if(list.contains(id)){ list.removeLast(); list.addFirst(id); }else{ if(list.size()>=3){ list.removeLast(); list.addFirst(id); }else{ list.addFirst(id); } } StringBuffer sb = new StringBuffer(); for(String s:list){ sb.append(s).append("-"); } String svalue = sb.toString().subString(0,sb.length-1); Cookie c = new Cookie("history",svalue); c.setPath("/path"); c.setMaxPath(60*60*24); response.addCookie(c); } request.getRequestDispatcher("/Demo/product.jsp").forward(request, response); } private static findCookie(Cookie[] cookies,Stirng name){ if(cookies == null){ return null; } for(Cookie cookie:cookies){ if(cookie.getName().equals(name)){ return cookie; } } return null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }JSPJava Server Pages(Java服务器页面) <%@ 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><span style="color:red">${ msg }</span><form action="/webfinal/UserServlet" method="post"> 用户<input type="text" name="username" /><br/> 密码<input type="password" name="password" /><br/> <input type="submit" value="提交" /></form></body></html>public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try { response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); User user = new User(); user.setUsername(username); user.setPassword(password); UserService userService = new UserService(); User existUser = userService.login(user); if(existUser == null){ request.setAttribute("msg", "用户或密码错误"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else{ response.setStatus(302); response.addHeader("Location", "/webfinal/success.html"); } } catch (SQLException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request,response); }}项目包设计简单设计: com.itheima 公司域名倒写 com.itheima.domain 存放javaBean com.itheima.dao 存放dao com.itheima.service 存放service com.itheima.web.servlet 存放servlet com.itheima.web.filter 存放filter com.itheima.utils 存放工具类 专业设计: com.itheima 公司域名倒写 com.itheima.domain 存放javaBean com.itheima.user.dao 存放dao com.itheima.user.service 存放service com.itheima.user.servlet 存放servlet com.itheima.utils 存放工具类
|