JavaWeb之会话:session和cookie

会话

会话字面意思:一次交流或交谈

在Web中,会话表示从浏览器打开某个网站,在这个网站中无论操作了什么,知道关闭浏览器,这一个过程,称之为一个会话。

怎么样算会话结束:

  • 客户端关闭了
  • 服务端销毁了

为什么要处理会话:

长期保持会话,无论用户关闭多少次浏览器,这个会话都要存在;

比喻:

你昨天来了教室,我今天需要知道你昨天来了教室;

  1. 你留下一个标记,让我知道你来过
  2. 你告诉我你来这边,我需要记录你来了;

你:客户端 我 :服务器

Javaweb中针对这两个不同的端,诞生两个小机制

cookie :在客户端留下一点东西,客户端下次带过来,我就知道你来过了。

比如说:我的店铺非常大,怎么证明你来过?

你开一个会员吧 , 我给你一张VIP卡,你下次带卡来,我就知道你来过了

Session:在服务器端登记你来过。

比如说:你去理发店。怎么证明你来过?

理发店收会员,在他的笔记本上记录了你的消息,下次你来直接报上大名就可以了。

cookie

构造器 :

Cookie cookie = new Cookie(String name,String value);
Cookie cookie = new Cookie(String name,String value);
Cookie cookie = new Cookie(String name,String value);

服务器响应cookie给客户端

Response.addCookie(Cookie);
Response.addCookie(Cookie);
Response.addCookie(Cookie);

服务查看用户带来的请求是否有cookie

Cookie[] cookies = Request.getCookie();
//可以使用cookie来验证用户是否来过
//判断cookies是否为空,然后遍历即可
Cookie.getName();
Cookie.getValue();

cookie测试用户是否来过

package com.westos.serlvet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieTest extends HttpServlet {

    boolean flag = false;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题:
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //检查请求的人是否带了Cookie
        //通过用户的请求,检查它是否有cookie
        Cookie[] cookies = request.getCookies();
        System.out.println("cookie:"+cookies);


        if (flag){//如果flag是真,来过
            if (cookies!=null){//你有cookie
                for (int i = 0; i < cookies.length ; i++) {
                    Cookie cookie = cookies[i];
                    if (cookie.getName().equals("lastLoginTime")){
                        response.getWriter().println("你上一次来的时间为:"+cookie.getValue());
                        System.out.println("刷新了cookie");
                    }
                }
            }
        }else { //如果flag是真,没来过
            response.getWriter().println("你是第一次来,还想要会员套餐");
            System.out.println("给该用户一个cookie");
        }

        //建立一个cookie
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        //设置cookie保存的时间 //cookie.setMaxAge();
        //把这个cookie发给客户端
        response.addCookie(cookie);

        //response.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
        flag = true;


    }
}

session

只要客户端一旦连接上服务器,服务器就会自动产生Session;

一个连接对应一个session,session可以在一个会话中传递信息;

通过setAttribute设置值。

通过getAttribute获得值。

由服务器端控制,服务器如果重启了,信息就会丢失!

案例:

package com.westos.serlvet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题:
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //Session由服务器自动创建,如何获得session

        //HttpSession 得到的sessioin对象
        HttpSession session = req.getSession();

        //得到sessionID,一次会话,一个seesionID;
        String id = session.getId();
        resp.getWriter().println("获得的sessionId:\n"+id);


        String name = "xiaoxuesheng";
        //向session中存入一个值;
        session.setAttribute("name",name);
        resp.getWriter().println("存入信息成功:"+name);

    }
}
package com.westos.serlvet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//获得session存入的值
public class SessionTest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题:
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        //获得
        HttpSession session = req.getSession();
        System.out.println("得到的SessionID:"+session.getId());


        String name = (String) session.getAttribute("name");
        resp.getWriter().println("得到的session存入的信息"+name);

        //Servlet  <  Seesion  <  WebContext

    }
}
  • 会话注销方法一:
session.invalidate();//通过代码注销会话
  • 会话注销方法二:
<!--session-config可以设置会话自动过期,时间分钟为单位-->
<session-config>
    <session-timeout>1</session-timeout>
</session-config>
发布了84 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/yalu_123456/article/details/96872348
今日推荐