A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© fxtahe 中级黑马   /  2018-7-20 14:26  /  2863 人查看  /  20 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

会话技术
用户打开一个浏览器访问页面,访问网站的很多页面,访问完成后将浏览器关闭的过程称为是一次会话.
常用会话技术
  • 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);        }JSP
Java 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           存放工具类


评分

参与人数 4技术分 +6 黑马币 +11 收起 理由
华林 + 5 很给力!
wangbiao138 + 1 神马都是浮云
15956215533 + 5
合肥就业部 + 6 赞一个!

查看全部评分

20 个回复

正序浏览
回复 使用道具 举报
回复 使用道具 举报
膜拜大佬
回复 使用道具 举报
厉害,继续努力坚持
回复 使用道具 举报
写的不错
回复 使用道具 举报
回复 使用道具 举报
真好,希望多一点这样的分享
回复 使用道具 举报
回复 使用道具 举报
写的好厉害的样子,可惜我看不懂。
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
        
回复 使用道具 举报
6666
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
12下一页
您需要登录后才可以回帖 登录 | 加入黑马