栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Day

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Day

文章目录

01-会话技术介绍(掌握)02-cookie概述(掌握)03-cookie基本使用(掌握)04-cookie执行流程(掌握)05-cookie相关设置(掌握)06-cookie的销毁(掌握)07-cookie练习(掌握)08-Session介绍(掌握)09-Session基本使用(掌握)10-Session执行流程(掌握)11-cookie相关配置(掌握)

01-会话技术介绍(掌握)

为什么?

ServeltRequest域对象的共享范围太小了;ServletContext域对象的共享范围太大了。 概述

当打开浏览器,访问网站地址后,会话开始,当关闭浏览器(或 者到了过期时间),会话结束。 分类

cookie : 浏览器端的会话技术

数据保存在浏览器 Session : 服务器端的会话技术

数据保存在服务器 作用

在一次会话中,存储数据并实现共享。 02-cookie概述(掌握)

概述

Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. 

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. 

The servlet sends cookies to the browser by using the HttpServletResponse.addcookie(javax.servlet.http.cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. 

The browser returns cookies to the servlet by adding fields to HTTP request headers. cookies can be retrieved from a request by using the HttpServletRequest.getcookies() method. Several cookies might have the same name but different path attributes. 

cookie对象,用于携带少量数据通过Servlet发送给浏览器,并且保存在浏览器,随后发送回服务器,所以往往用于会话管理;cookie对象,有必须属性name和value,还有一些可选属性path、a maximum age,不同的浏览器对可选属性的支持不太一样;服务器发送cookie给浏览器,是通过HttpServletResponse.addcookie操作响应头Set-cookie来完成;浏览器,同一时间,每个项目最多20个cookie,总共300个cookie,每个cookie中的数据最多4KB;浏览器发送cookie给服务器,服务器是通过 HttpServletRequest.getcookies操作请求头cookie来获取。

常用属性

name、value、path、a maximum age 03-cookie基本使用(掌握)

代码实现

@WebServlet("/demo01")
public class Demo01Servlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cookie cookie = new cookie("msg","hello");
        //操作响应头Set-cookie
        resp.addcookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
@WebServlet("/demo02")
public class Demo02Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取浏览器发送过来的cookie,通过请求头cookie来获取
        cookie[] cookies = req.getcookies();
        cookie mycookie = null;
        if (null == cookies || 0 == cookies.length) {

        } else {
            for (cookie cookie : cookies) {
                if ("msg".equals(cookie.getName())) {
                    mycookie = cookie;
                }
            }
        }

        if (null == mycookie) {
            System.out.println("没有找到cookie");
        } else {
            System.out.println("name = " + mycookie.getName() + " , value = " + mycookie.getValue());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
04-cookie执行流程(掌握)

执行流程

05-cookie相关设置(掌握)

①值限制

cookie 的值不能包含逗号、分号、空格,不能以$开头。

②存活时长限制

-1 : 默认值,会话结束,cookie就销毁正数:cookie存活时长,以秒为单位0 : 立即销毁cookie

③访问路径限制

默认值:"/项目访问路径";设置什么时候需要携带cookie

①值限制

@WebServlet("/demo03")
public class Demo03Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cookie cookie = new cookie("msg2","hello,2");//错误示范
        resp.addcookie(cookie);
    }

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

②存活时长限制

@WebServlet("/demo04")
public class Demo04Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cookie cookie = new cookie("msg3", "hello3");
        cookie.setMaxAge(7 * 24 * 60 * 60);
        resp.addcookie(cookie);
    }

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

③访问路径限制

@WebServlet("/demo05")
public class Demo05Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cookie cookie = new cookie("msg4", "hello4");
        cookie.setPath(req.getContextPath() + "/demo02");
        resp.addcookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
06-cookie的销毁(掌握)

开发步骤

①创建cookie对象

指定name属性 ②设置path属性③设置maxAge=0④将cookie响应给浏览器

代码实现

@WebServlet("/demo06")
public class Demo06Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //①创建cookie对象
        cookie cookie = new cookie("msg4", "aaa");
        //②设置path属性
        cookie.setPath("/day08/myDemo02");
        //③设置maxAge=0
        cookie.setMaxAge(0);
        //④将cookie响应给浏览器
        response.addcookie(cookie);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
07-cookie练习(掌握)

需求

显示商品浏览记录

开发步骤

①定义shopping.html

显示商品列表 ②添加历史记录③获取历史记录④展示历史记录

①定义shopping.html

public void toShoppingListPage(HttpServletRequest request, HttpServletResponse response) {
    try {
        processTemplate("shopping-list", request, response);
    } catch (IOException e) {
        e.printStackTrace();
    }
}



    
    商品列表



西游记
红楼梦
三国演义
水浒传
查看历史记录

②添加历史记录

public void addHistory(HttpServletRequest request, HttpServletResponse response){
    String id = request.getParameter("id");
    System.out.println("ShoppingServlet addHistory " + id);

    cookie[] cookies = request.getcookies();
    cookie mycookie = null;
    if (null == cookies || 0 == cookies.length) {
    } else {
        for (cookie cookie : cookies) {
            if ("history".equals(cookie.getName())) {
                mycookie = cookie;
            }
        }
    }
    if (null == mycookie) {
        //第一次浏览
        mycookie = new cookie("history",id);
    } else {
        //不是第一次浏览器 , 商品之前是否浏览过?
        //0-1
        String historyStr = mycookie.getValue();
        if (!historyStr.contains(id)) {
            historyStr = historyStr + "-" + id;
        }
        mycookie.setValue(historyStr);
    }

    response.addcookie(mycookie);


}

③获取历史记录

public void showHistory(HttpServletRequest request, HttpServletResponse response) {
    //获取历史浏览记录
    String[] shoppingNames = {"西游记", "红楼梦", "三国演义", "水浒传"};
    cookie[] cookies = request.getcookies();
    cookie mycookie = null;
    if (null == cookies || 0 == cookies.length) {
    } else {
        for (cookie cookie : cookies) {
            if ("history".equals(cookie.getName())) {
                mycookie = cookie;
            }
        }
    }
    List shoppingNameList = new ArrayList<>();
    if (null == mycookie) {
        //没有历史记录
    } else {
        //有历史记录 : 0-1-2-3
        String historyStr = mycookie.getValue();
        String[] historyIndexStrs = historyStr.split("-");
        for (String historyIndexStr : historyIndexStrs) {
            Integer historyIndex = Integer.parseInt(historyIndexStr);
            String shoppingName = shoppingNames[historyIndex];
            shoppingNameList.add(shoppingName);
        }
    }

    request.setAttribute("shoppingNameList", shoppingNameList);
    try {
        processTemplate("shopping-history", request, response);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

④展示历史记录




    
    历史列表





    您还没有浏览过任何商品,去看看!



    商品浏览记录如下:
08-Session介绍(掌握)

概述

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. 

Session对象,提供了一种方式可以在多个web页面之间实现存储数据并共享。只不过在客户端保存的是一个特殊标识,而共享的数据保存到了服务器端的内存对象中。每次请求 时,浏览器都会将特殊标识携带到服务器端,根据这个标识来找到对应的内存空间,从而实现共享。

三大域对象

ServletRequest、HttpSesion、ServletContext 09-Session基本使用(掌握)

代码实现

@WebServlet("/demo07")
public class Demo07Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Demo07Servlet session = " + session.getId());
        session.setAttribute("msg","hello");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
@WebServlet("/demo08")
public class Demo08Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Demo08Servlet session = " + session.getId());
        Object msg = session.getAttribute("msg");
        System.out.println("msg = " + msg);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
@WebServlet("/demo09")
public class Demo09Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Demo09Servlet session = " + session.getId());
        session.removeAttribute("msg");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
10-Session执行流程(掌握)

执行流程

11-cookie相关配置(掌握)

①生命周期

默认情况下,Session对象存活时长为30分钟;可以通过在web.xml中,设置来对session存活时长进行配置;也可以通过session.setMaxInactiveInterval()进行配置

②session销毁

通过session.invalidate()方法进行销毁

①生命周期


    1

@WebServlet("/demo10")
public class Demo10Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(10);
        System.out.println("Demo10Servlet session = " + session.getId());
        session.setAttribute("msg","hello");

    }

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

②session销毁

@WebServlet("/demo14")
public class Demo14Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Demo14Servlet session = " + session.getId());
        session.invalidate();

    }

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

注意事项

当用户关闭浏览器,并没有销毁服务器中的Sesion对象,它会遵守web.xml中30分钟的默认存活时长;但是,浏览器中的cookie销毁了,意味着JSESSIONID没有了,意味着后续的请求,服务器认为是一个新的会话,所以会创建新的Session对象。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770533.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号