Java进阶学习第五天(会话管理)

一、会话管理

1、会话管理: 管理浏览器客户端 和 服务器端之间会话过程中产生的会话数据。

2、request域对象
① 小张:输入“张三” (保存数据:context.setAttribute(“name”,”张三”)) > 用户主页(显示“张三”)
② 小李:输入“李四”(保存数据:context.setAttribute(“name”,”李四”)) > 用户主页(显示“李四”)

问题: context是所有用户公有的资源,会覆盖数据。

3、context域对象
小张:输入“张三” (保存数据:context.setAttribute(“name”,”张三”)) > 用户主页(显示“张三”)

问题: 一定要使用转发技术来跳转页面

4、会话技术
① Cookie技术:会话数据保存在浏览器客户端
② Session技术:会话数据保存在服务器端

二、Cookie技术

1、Cookie技术核心:Cookie类:用于存储会话数据
① 构造Cookie对象
Cookie(java.lang.String name, java.lang.String value)
② 设置cookie
void setPath(java.lang.String uri) :设置cookie的有效访问路径
void setMaxAge(int expiry): 设置cookie的有效时间
void setValue(java.lang.String newValue):设置cookie的值
③ 发送cookie到浏览器端保存
void response.addCookie(Cookie cookie) :发送cookie
④ 服务器接收cookie
Cookie[] request.getCookies() :接收cookie

public class CookieDemo1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie cookie1 = new Cookie("name","eric");
        //Cookie cookie1 = new Cookie("email","[email protected]");
        //Cookie cookie2 = new Cookie("email","[email protected]");

        //1)设置cookie的有效路径。默认情况:有效路径在当前web应用下/day11
        //cookie1.setPath("/day11");
        //cookie2.setPath("/day12");

        //2)设置cookie的有效时间
        //正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!零:表示删除同名的cookie数据
        //cookie1.setMaxAge(20); //20秒,从最后不调用cookie开始计算
        cookie1.setMaxAge(-1); //cookie保存在浏览器内存(会话cookie)
        //cookie1.setMaxAge(0);

        //2.把cookie数据发送到浏览器(通过响应头发送: set-cookie名称)
        //response.setHeader("set-cookie", cookie.getName()+"="+cookie.getValue()+",[email protected]");
        //推荐使用这种方法,避免手动发送cookie信息
        response.addCookie(cookie1);
        //response.addCookie(cookie2);
        //response.addCookie(cookie1);

        //3.接收浏览器发送的cookie信息
        /*String name = request.getHeader("cookie");
        System.out.println(name);*/
        Cookie[] cookies = request.getCookies();
        //注意:判断null,否则空指针
        if(cookies!=null){
            //遍历
            for(Cookie c:cookies){
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+"="+value);
            }
        }else{
            System.out.println("没有接收cookie数据");
        }   
    }
}

2、Cookie原理
① 服务器创建cookie对象,把会话数据存储到cookie对象中
new Cookie("name","value");
② 服务器发送cookie信息到浏览器
response.addCookie(cookie);
举例: set-cookie: name=eric (隐藏发送了一个set-cookie名称的响应头)
③ 浏览器得到服务器发送的cookie,然后保存在浏览器端
④ 浏览器在下次访问服务器时,会带着cookie信息
举例: cookie: name=eric (隐藏带着一个叫cookie名称的请求头)
⑤ 服务器接收到浏览器带来的cookie信息
request.getCookies();

3、Cookie的细节
void setPath(java.lang.String uri) :设置cookie的有效访问路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。
void setMaxAge(int expiry) : 设置cookie的有效时间
◆ 正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间
◆ 负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了
◆ 零:表示删除同名的cookie数据
③ Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB

4、案例- 显示用户上次访问的时间

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String curTime = format.format(new Date());

        //取得cookie
        Cookie[] cookies = request.getCookies();
        String lastTime = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("lastTime")){
                    //有lastTime的cookie:已经是第n次访问
                    lastTime = cookie.getValue();//上次访问的时间
                    //第n次访问
                    //1.把上次显示时间显示到浏览器
                    response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime);
                    //2.更新cookie
                    cookie.setValue(curTime);
                    cookie.setMaxAge(1*30*24*60*60);
                    //3.把更新后的cookie发送到浏览器
                    response.addCookie(cookie);
                    break;
                }
            }
        }

        //第一次访问(没有cookie或有cookie,但没有名为lastTime的cookie)
        if(cookies==null || lastTime==null){
            //1.显示当前时间到浏览器
            response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);
            //2.创建Cookie对象
            Cookie cookie = new Cookie("lastTime",curTime);
            cookie.setMaxAge(1*30*24*60*60);//保存一个月
            //3.把cookie发送到浏览器保存
            response.addCookie(cookie);
        }
    }

5、案例-查看用户浏览器过的商品
① 类分包:
◆ gz.itcast.hist.entity:存放实体对象
◆ gz.itcast.hist.dao:Data Access Object数据访问对象。存放实体对象的操作方法(CRUD方法-create read update delete)
◆ gz.itcast.hist.servlet:存放servlet程序
◆ gz.itcast.hist.util:存放工具类
◆ gz.itcast.hist.test:存放测试类
② entity

public class Product {

    private String id;
    private String proName;
    private String proType;
    private double price;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getProName() {
        return proName;
    }
    public void setProName(String proName) {
        this.proName = proName;
    }
    public String getProType() {
        return proType;
    }
    public void setProType(String proType) {
        this.proType = proType;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Product(String id, String proName, String proType, double price) {
        super();
        this.id = id;
        this.proName = proName;
        this.proType = proType;
        this.price = price;
    }
    public Product() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", price=" + price + ", proName="
                + proName + ", proType=" + proType + "]";
    }
}

③ dao

public class ProductDao {
    //模拟"数据库",存放所有商品数据
    private static List<Product> data = new ArrayList<Product>();

    //初始化商品数据
    static{
        //只执行一次
        for(int i=1;i<=10;i++){
            data.add(new Product(""+i,"笔记本"+i,"LN00"+i,34.0+i));
        }
    }

    //提供查询所有商品的方法
    public List<Product> findAll(){
        return data;
    }

    //提供根据编号查询商品的方法
    public Product findById(String id){
        for(Product p:data){
            if(p.getId().equals(id)){
                return p;
            }
        }
        return null;
    }
}

④ servlet

public class ListServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //1.读取数据库,查询商品列表
        ProductDao dao = new ProductDao();
        List<Product> list = dao.findAll();

        //2.把商品显示到浏览器
        PrintWriter writer = response.getWriter();
        String html = "";   
        html += "<html>";
        html += "<head>";
        html += "<title>显示商品列表</title>";
        html += "</head>";
        html += "<body>";
        html += "<table border='1' align='center' width='600px'>";
        html += "<tr>";
        html += "<th>编号</th><th>商品名称</th><th>商品型号</th><th>商品价格</th>";
        html += "</tr>";
        //遍历商品
        if(list!=null){
            for(Product p:list){
                html += "<tr>";
                // /day11_hist/DetailServlet?id=1 访问DetailSErvlet的servlet程序,同时传递 名为id,值为1 的参数
                html += "<td>"+p.getId()+"</td><td><a href='"+request.getContextPath()+"/DetailServlet?id="+p.getId()+"'>"+p.getProName()+"</a></td><td>"+p.getProType()+"</td><td>"+p.getPrice()+"</td>";
                html += "<tr>";
            }
        }
        html += "</table>";

        //显示浏览过的商品
        html += "最近浏览过的商品:<br/>";
        //取出prodHist的cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("prodHist")){
                    String prodHist = cookie.getValue(); // 3,2,1
                    String[] ids = prodHist.split(",");
                    //遍历浏览过的商品id
                    for (String id : ids) {
                        //查询数据库,查询对应的商品
                        Product p = dao.findById(id);
                        //显示到浏览器
                        html += ""+p.getId()+"&nbsp;"+p.getProName()+"&nbsp;"+p.getPrice()+"<br/>";
                    }
                }
            }
        }
        html += "</body>";
        html += "</html>";
        writer.write(html);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
public class DetailServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //1.获取编号
        String id = request.getParameter("id");

        //2.到数据库中查询对应编号的商品
        ProductDao dao = new ProductDao();
        Product product = dao.findById(id);

        //3.显示到浏览器
        PrintWriter writer = response.getWriter();
        String html = "";
        html += "<html>";
        html += "<head>";
        html += "<title>显示商品详细</title>";
        html += "</head>";
        html += "<body>";
        html += "<table border='1' align='center' width='300px'>";
        if(product!=null){
            html += "<tr><th>编号:</th><td>"+product.getId()+"</td></tr>";
            html += "<tr><th>商品名称:</th><td>"+product.getProName()+"</td></tr>";
            html += "<tr><th>商品型号:</th><td>"+product.getProType()+"</td></tr>";
            html += "<tr><th>商品价格:</th><td>"+product.getPrice()+"</td></tr>";
        }   
        html += "</table>";
        html += "<center><a href='"+request.getContextPath()+"/ListServlet'>[返回列表]</a></center>";
        html += "</body>";
        html += "</html>";
        writer.write(html);

        //创建cookie,并发送
        //1.创建cookie
        Cookie cookie = new Cookie("prodHist",createValue(request,id));
        cookie.setMaxAge(1*30*24*60*60);//一个月
        //2.发送cookie
        response.addCookie(cookie);
    }

    /**
     * 生成cookie的值
     * 分析:
     *          当前cookie值                     传入商品id               最终cookie值
     *      null或没有prodHist          1                     1    (算法: 直接返回传入的id )
     *             1                  2                     2,1 (没有重复且小于3个。算法:直接把传入的id放最前面 )
     *             2,1                1                     1,2(有重复且小于3个。算法:去除重复id,把传入的id放最前面 )
     *             3,2,1              2                     2,3,1(有重复且3个。算法:去除重复id,把传入的id放最前面)
     *             3,2,1              4                     4,3,2(没有重复且3个。算法:去最后的id,把传入的id放最前面)
     * @return
     */
    private String createValue(HttpServletRequest request,String id) {

        Cookie[] cookies = request.getCookies();
        String prodHist = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("prodHist")){
                    prodHist = cookie.getValue();
                    break;
                }
            }
        }

        // null或没有prodHist
        if(cookies==null || prodHist==null){
            //直接返回传入的id
            return id;
        }
        // 3,21          2
        //String -> String[] ->  Collection :为了方便判断重复id
        String[] ids = prodHist.split(",");
        Collection colls = Arrays.asList(ids); //<3,21>
        // LinkedList 方便地操作(增删改元素)集合
        // Collection -> LinkedList
        LinkedList list = new LinkedList(colls);

        //不超过3个
        if(list.size()<3){
            //id重复
            if(list.contains(id)){
                //去除重复id,把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //直接把传入的id放最前面
                list.addFirst(id);
            }
        }else{
            //等于3个
            //id重复
            if(list.contains(id)){
                //去除重复id,把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //去最后的id,把传入的id放最前面
                list.removeLast();
                list.addFirst(id);
            }
        }

        // LinedList -> String 
        StringBuffer sb = new StringBuffer();
        for (Object object : list) {
            sb.append(object+",");
        }
        //去掉最后的逗号
        String result = sb.toString();
        result = result.substring(0, result.length()-1);
        return result;
    }

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

三、Session技术

1、Cookie的局限
① Cookie只能存字符串类型,不能保存对象
② 只能存非中文
③ 1个Cookie的容量不超过4KB

如果要保存非字符串,超过4kb内容,只能使用session技术!!!

2、Session特点:会话数据保存在服务器端(内存中)

3、Session技术核心:HttpSession类:用于保存会话数据
① 创建或得到session对象
HttpSession getSession()
HttpSession getSession(boolean create)
② 设置session对象
void setMaxInactiveInterval(int interval) : 设置session的有效时间
void invalidate() : 销毁session对象
java.lang.String getId() : 得到session编号
③ 保存会话数据到session对象
void setAttribute(java.lang.String name, java.lang.Object value): 保存数据
java.lang.Object getAttribute(java.lang.String name): 获取数据
void removeAttribute(java.lang.String name): 清除数据

public class SessionDemo1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.创建session对象
        HttpSession session = request.getSession();

        //得到session编号
        System.out.println("id="+session.getId());

        //修改session的有效时间
        //session.setMaxInactiveInterval(20);

        //手动发送一个硬盘保存的cookie给浏览器
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);
        //2.保存会话数据
        session.setAttribute("name", "rose");
    }
}
public class SessionDemo2 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.得到session对象
        HttpSession session = request.getSession(false);
        if(session==null){
            System.out.println("没有找到对应的sessino对象");
            return;
        }

        //得到session编号
        System.out.println("id="+session.getId());

        //2.取出数据
        String name = (String)session.getAttribute("name");
        System.out.println("name="+name);
    }
}
public class DeleteSession extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();//手动销毁
        }
        System.out.println("销毁成功");
    }
}

3、Session原理
① 问题: 服务器能够识别不同的浏览者!
② 前提: 在哪个session域对象保存数据,就必须从哪个域对象取出!
③ 现象
◆ 浏览器1:(给s1分配一个唯一的标记:s001,把s001发送给浏览器)
1)创建session对象,保存会话数据
HttpSession session = request.getSession(); —— 保存会话数据 s1
◆ 浏览器1的新窗口(带着s001的标记到服务器查询,s001对应s1对象,返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); —— 可以取出 s1
◆ 新的浏览器1:(没有带s001,不能返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); —— 不可以取出 s2
◆ 浏览器2:(没有带s001,不能返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); —— 不可以取出s3

4、代码解读:HttpSession session = request.getSession();
① 第一次访问创建session对象,给session对象分配一个唯一的ID,叫JSESSIONID
② 把JSESSIONID作为Cookie的值发送给浏览器保存
③ 第二次访问的时候,浏览器带着JSESSIONID的cookie访问服务器
④ 服务器得到JSESSIONID,在服务器的内存中搜索是否存放对应编号的session对象
⑤ 如果找到对应编号的session对象,直接返回该对象
⑥ 如果找不到对应编号的session对象,创建新的session对象,继续走①的流程

结论:通过JSESSION的cookie值在服务器找session对象!

5、Sesson细节
java.lang.String getId() : 得到session编号
② 两个getSession方法
getSession(true) / getSession() : 创建或得到session对象,没有匹配的session编号,自动创建新的session对象
getSession(false): 得到session对象,没有匹配的session编号,返回null
void setMaxInactiveInterval(int interval):设置session的有效时间,单位秒
④ session对象销毁时间
◆ 默认情况30分服务器自动回收
◆ 修改session回收时间
◆ 全局修改session有效时间

<!-- 修改session全局有效时间:分钟 -->
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

◆ 手动销毁session对象
void invalidate(): 销毁session对象
4)如何避免浏览器的JSESSIONID的cookie随着浏览器关闭而丢失的问题

//手动发送一个硬盘保存的cookie给浏览器
Cookie c = new Cookie("JSESSIONID",session.getId());
c.setMaxAge(60*60);
response.addCookie(c);

6、用户登录场景

<html>
  <head>
    <title>登录页面</title>
  </head>
  <body>
    <form action="/day12/LoginServlet" method="post">
        用户名:<input type="text" name="userName"/>
        <br/>
        密码:<input type="text" name="userPwd"/>
        <br/>
        <input type="submit" value="登录"/>
    </form>
  </body>
</html>
<html>
  <head>
    <title>信息提示页面</title>
  </head>
  <body>
    <font color='red' size='3'>亲, 你的用户名或密码输入有误!请重新输入!</font><br/>
    <a href="/day12/login.html">返回登录页面</a>
  </body>
</html>
/**
 * 处理登录的逻辑
 */
public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1.接收参数
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");

        //2.判断逻辑
        if("eric".equals(userName)
                 && "123456".equals(userPwd)){
            //登录成功
            /**
             * 分析:
             *    context域对象:不合适,可能会覆盖数据。
             *    request域对象: 不合适,整个网站必须得使用转发技术来跳转页面
             *    session域对象:合适。
             */
            /*
            request.setAttribute("loginName", userName);
            //request.getRequestDispatcher("/IndexServlet").forward(request, response);
            response.sendRedirect(request.getContextPath()+"/IndexServlet");
            */  
            /**
             * 一、登录成功后,把用户数据保存session对象中
             */
            //1.创建session对象
            HttpSession session = request.getSession();
            //2.把数据保存到session域中
            session.setAttribute("loginName", userName);
            //3.跳转到用户主页
            response.sendRedirect(request.getContextPath()+"/IndexServlet");    
        }else{
            //登录失败
            //请求重定向
            response.sendRedirect(request.getContextPath()+"/fail.html");
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * 用户主页的逻辑
 */
public class IndexServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        String html = "";

        //接收request域对象的数据

        //String loginName = (String)request.getAttribute("loginName");

        //二、在用户主页,判断session不为空且存在指定的属性才视为登录成功!才能访问资源。
        //从session域中获取会话数据

        //1.得到session对象
        HttpSession session = request.getSession(false);
        if(session==null){
            //没有登录成功,跳转到登录页面
    response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //2.取出会话数据
        String loginName = (String)session.getAttribute("loginName");
        if(loginName==null){
            //没有登录成功,跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        html = "<html><body>欢迎回来,"+loginName+",<a href='"+request.getContextPath()+"/LogoutServlet'>安全退出</a></body></html>";    
        writer.write(html);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * 退出逻辑
 */
public class LogoutServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //三、安全退出:删除掉session对象中指定的loginName属性即可!  

        //1.得到session对象
        HttpSession session = request.getSession(false);
        if(session!=null){
            //2.删除属性
            session.removeAttribute("loginName");
        }   
        //2.回来登录页面
        response.sendRedirect(request.getContextPath()+"/login.html");  
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

猜你喜欢

转载自blog.csdn.net/Mr_GaoYang/article/details/82379288