Cookie会话技术重要笔记及案例

第一部分:今日技术操作及其概述

1.记录用户的上次登陆访问时间
*什么是会话: 当用户打开浏览器访问服务器的任意资源,直到最后关闭流程的过程.称之为一次会话.
*作用:保存用户的私有数据.
*分类:
按照保存数据位置不同划分:
Cookie : 浏览器端会话技术
Session: 服务器端会话技术.

2.Cookie技术的使用及常用API
*创建一个Cookie对象 new Cookie(String name,String value);
*向浏览器保存数据 response.addCookie(Cookie cookie);
*获得浏览器中带过来的Cookie Cookie[] request.getCookies();
*Cookie的常用API——————–
getName();
getValue();
setPath(String path); 设置Cookie的有效路径
SetMaxAge(int maxAge); 设置Cookie的有效时间(默认时间为秒)
*Cookie的分类有关:——————
*会话级别的Cookie:默认的Cookie.关闭浏览器Cookie就会销毁.
*持久级别的Cookie:可以设置Cookie的有效时间.那么关闭浏览器Cookie还会存在. 手动销毁持久性Cookie.

3.JSP
*什么是JSP :Java Server Pages(Java服务器端页面) 动态的网页开发技术. 本质上就是Servlet
执行原理: .jsp –> .java –>.class —>响应浏览器
*作用: 编写HTML标签. 可以在JSP编写JAVA代码
*特点: 可以在JSP编写JAVA代码
*JSP脚本元素: <% %> :翻译成类的service方法内部的内容. 定义变量,定义类,直接写代码块.
<%= %> :翻译成service方法内部的out.print(); 【里面不能有冒号,上面两个可以有冒号】

4.项目包结构设计(老师扩展)
*简单设计
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 存放工具类

5.删除Cookie:
1. 创建一个同名cookie
new Cookie(“history”,”xxx”)
2. 设置响应有效访问路径
cookie.setPath(“/day15”)
3. 设置cookie的有效时间
cookie.setMaxAge(0)
4. 返回浏览器
response.addCookie(cookie)

第二部分:今日代码实现

/**
* 用户登录Servlet
*
*/
public class UserServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        //响应乱码处理
        response.setContentType("text/html;charset=utf-8");
        //请求乱码
        request.setCharacterEncoding("utf-8");


        // 1. 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 2. 封装数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 3. 调用业务层处理数据
        UserService service = new UserService();
        User existUser = service.login(user);

        // 4. 页面跳转
        if (existUser == null) {
            // 用户名密码输入错误.登录失败
            request.setAttribute("msg", "用户名密码输入错误~~~");     【<div style="color:red">${msg} </div>在jsp文件下的会员登陆下写,在<li><a href="/demo2/login.jsp">登录</a></li>在index.html里面改下jsp】
            // 请求转发
            request.getRequestDispatcher("/demo2/login.jsp").forward(request, response);
        } else {
            // 登录成功: 重定向(防止重复提交)
            // response.sendRedirect(request.getContextPath()+"/index.html");
            /**
     * 获得浏览器中带过来的所有的Cookie信息,从数组中查找有没有指定名称的Cookie
     * 判断用户是否是第一次访问:(从数组中没有找到指定名称的Cookie)
     * * 如果是第一次:显示欢迎,记录当前访问的时间存入到Cookie中.
     * * 如果不是第一次:显示欢迎,上一次访问时间,同时记录当前访问的时间存入到Cookie中。
     */

            /* modified by fei.peng 2018-06-20 添加记录用户的上次访问时间 start * */     【在公司专业备注】

            // 1. 判断用户是否是第一次登录
            // 获取浏览器发送过来的所有cookie
            Cookie[] cookies = request.getCookies();
            // 从数组中查找指定名称的Cookie:
            Cookie cookie  = findCookie(cookies, "lastTime");    //往回存的时候名称想叫啥叫啥,上一次访问时间的名字(就是最后一次访问的时间)

            // 判断是否是第一次:
            if(cookie ==null){
                // 用户第一次访问
                response.getWriter().print("<h2>欢迎您第一次访问~~~</h2>");
            }else{
                // 不是第一次
                String time = cookie.getValue();   【最后一次访问的时间,给个返回值time,那么time就是上一次登陆的时间】
                response.getWriter().print("<h2>欢迎您再次访问~~~,您上次的访问时间: "+time+"</h2>");
                //response.sendRedirect("/day16/demo2/index.html");   【重定向到首页,但是没刷新,跳的太快,显示不了上次登陆的时间,所以下面给他刷新了5秒后跳转到首页】
                response.getWriter().println("<h3>页面将在5秒后跳转到首页!</h3>");
                response.setHeader("Refresh", "5;url=/day16/demo2/index.html");  //刷新,5秒后从上次访问时间跳转到首页
            }
                // 创建一个Cookie对象:
                Cookie c = new Cookie("lastTime", new Date().toLocaleString());   【直接用日期类型,不用像第一种,先写long类型,打印看不懂,还要转换成Date类型,第二种就是直接new Date(),一步到位】
                // 设置Cookie的有效路径
                c.setPath("/day16");  【不写也没事,写了只是为了删除其持久性】
                // 设置Cookie的有效时间
                c.setMaxAge(60 * 60*24);
                // 保存到浏览器端:
                response.addCookie(c);

            /* modified by fei.peng 2018-06-20 添加记录用户的上次访问时间 end * */

        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

/**
 * 根据cookie名称从数组中查询指定cookie
 * @param cookies
 * @param cookeName
 * @return
 */
public Cookie findCookie(Cookie[] cookies, String cookieName) {
    //先判断数组是不是空的,如果数组是空的,就是第一次访问
    if (cookies == null) {
        return null;
    }

    for (Cookie cookie : cookies) {
        //如果数组里面有记录,就拿cookieName和lastTime对应的getName进行比较,如果有,就代表我登陆过,返回即可
        if (cookieName.equals(cookie.getName())) {
            // 找到指定cookie
            return cookie;
        }
    }
    return null;

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
    doGet(request, response);
}

}

猜你喜欢

转载自blog.csdn.net/pf503603/article/details/82048608