Cookie、Session的运用(代码)

1. Cookie、Session

1.1、会话

会话:用户打开了一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话

**有状态会话:**一个网站,怎么证明你来过?

  1. 服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
  2. 服务器登记你来过了,下次你来的时候就可以匹配;session

1.2保存会话的两种技术

cookie

  • 客户端技术(响应,请求)

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在Session中

常见场景:网站登录之后,下次不用在登录了,第二次访问直接就上去了!

1.3、Cookie

1、从请求中拿到cookie信息

2.服务器响应给客户端cookie

 	Cookie[] cookies = req.getCookies(); //获取cookie
	cookie.getName()  //获取cookie中的key
    cookie.getValue() //获取cookie中的值
   	new Cookie("lastLoginTime", System.currentTimeMillis()+"") //新建一个1cookie
    cookie.setMaxAge(24*60*60); 设置cookie的有效期
 	resp.addCookie(cookie); //响应给客户端一个cookie

cookie:一般会保存在本地的用户目录下appdata

一个网站cookie是否存在上限!细节问题

  • 一个Cookie只能保存一个信息;
  • 一个web站点可以给浏览器发送多个cookie,最大存放20个
  • cookie大小有限制;
  • 300个cookie浏览器上限

删除Cookie

  • 不设置有效期,关闭浏览器,自动失效;
  • 设置有效期时间为0;
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        //cookie,服务器从客户端获取
        Cookie[] cookies = req.getCookies();//这里返回数据,说明cookie可能存在多个
        //判断cookie是否存在
        if(cookies!=null)
        {
            //如果存在
            out.write("你上次访问的时间是:");
            for (int i = 0; i <cookies.length ; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的名字
                if (cookie.getName().equals("lastLoginTime"))
                {
                    //获取cookie中的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }
        else
        {
            System.out.println("这是你第一次访问网站");
        }
        //服务器给客户端响应一个cookie;
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        //cookie有效为一天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}

编码解码:

URLEncoder.encode("小明","UTF-8")  //编码
URLDecoder.decode(cookie.getValue(),"UTF-8") //解码

1.4、Session(重点)

什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Session对象
  • 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就会存在;
  • 用户登录之后,整个网站都可以访问!---->保存购物车的信息…

Session和Cookie的区别:

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存
  • Session把用户的数据写到用户独占Session中,服务器端保存(重要的信息,减少资源浪费)
  • Session对象由服务器创建;

使用场景:

  • 保存一个登陆用户的信息;
  • 购物车信息;
  • 在整个网站中经常会使用的数据。

使用Session:

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到Session
        HttpSession session = req.getSession();
        //给Session中存东西
        session.setAttribute("name",new Person("小明",18));
        //获取Session的ID
        String id = session.getId();
        //判断Session是不是新创建的
        if(session.isNew())
        {
            resp.getWriter().write("session创建成功,ID"+id);
        }
        else {
            resp.getWriter().write("session已经在浏览器中存在了"+id);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

}



public class SessionDemo02 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到Session
        HttpSession session = req.getSession();
        Person name = (Person)session.getAttribute("name");
        System.out.println(name);
        //手动注销
       // session.removeAttribute("name");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
 <servlet>
        <servlet-name>Cookie</servlet-name>
        <servlet-class>com.maple.servlet.CookieDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Cookie</servlet-name>
        <url-pattern>/c1</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>Session</servlet-name>
        <servlet-class>com.maple.servlet.SessionDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Session</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>Session1</servlet-name>
        <servlet-class>com.maple.servlet.SessionDemo02</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Session1</servlet-name>
        <url-pattern>/s2</url-pattern>
    </servlet-mapping>
    <!--设置Session默认的失效时间-->
    <session-config>
        <!--1分钟Session自动失效-->
        <session-timeout>1</session-timeout>
    </session-config>

Session的注销:

        //手动注销
       // session.removeAttribute("name");

会话自动过期:web.xml中配置

    <!--设置Session默认的失效时间-->
    <session-config>
        <!--1分钟Session自动失效-->
        <session-timeout>1</session-timeout>
    </session-config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值