Java 之 HttpSession

HttpSession

/*
 * HttpSession 服务端的技术
 * 服务器会为每一个用户创建一个独立的 session
 * 
 * HttpSession 原理
 * 当用户第一次访问 Servlet 时,服务器端对给该用户创建一个独立的 Session, 并且生成一个 SessionID
 * 这个 SessionID 在响应浏览器的时候,会被装进 cookie 中
 * 从而被保存到浏览器中
 * 当用户再一次访问 Servlet 的时候
 * 请求中会携带着 cookie 中的 SessionID 去访问
 * 服务器会根据这个 SessionID 去查看是否有对应的 Session 对象
 * 有,则直接调用
 * 无,则创建一个(相当于用户第一次访问)(看病案例)
 * 
 * 域的范围
 * Context 域 > Session 域 > Request 域
 * Session 域只要会话不结束就会存在,但是Session 域有默认存活时间-30分钟
 * 
 * 模拟购物功能
 * 大概需要几个页面来完成 --- 需要几个 Servlet 类
 * 需要3个 Servlet 类
 * session 中保存什么数据合适,添加一个保存书的容器
 * 书类:id,bookname
 * 模拟假数据,逻辑和功能跑通了,再连接数据库
 * 模拟假数据的类
 * map 集合 HashMap
 * 方法:根据 ID 获取对应的书
 */
@SuppressWarnings("serial")
public class Demo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 获取参数
        String username = request.getParameter("username");

        // 获取 session 对象
        HttpSession session = request.getSession();
        // 保存数据
        session.setAttribute("username", username);
        // 打印 SessionID
        System.out.println(session.getId());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
/*
 * 测试获取 session 域中的数据
 */
public class Demo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 获取 session 域中的数据
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        // 响应到网页上
        response.getWriter().write(username + " " + session.getId());

    }

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

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 获取 session 对象
        HttpSession session = request.getSession();
        ArrayList car = (ArrayList) session.getAttribute("car");
        PrintWriter out = response.getWriter();
        if (car != null) {
            // 遍历输出
            for (Book book : car) {
                out.write(book + "
"
); } out.write("会到商品页面"); } else { out.write("当前无任何商品"); response.setHeader("refresh", "3;url=" + request.getContextPath() + "/showallbooks"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } /* * 展示商品列表 */ public class ShowAllBooks extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); /* * 1.获取所有书 2.遍历输出到网页上 3.需要给书名添加一个连接(a 标签) 4.点击书名的时候,能知道点的是那本书 */ PrintWriter out = response.getWriter(); HashMap books = BookUtil.getBooks(); for (String key : books.keySet()) { Book book = books.get(key); out.write("">" + book + "
"); } // 添加查看购物车连接 out.write("查看购物车"); // 设置 session 有效时间 request.getSession().setMaxInactiveInterval(10); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } /* * 模拟假数据 */ public class BookUtil { // 声明一个保存书的容器 private static HashMap books = new HashMap<>(); // 添加数据 static { books.put("1", new Book("1", "降龙十八掌")); books.put("2", new Book("2", "打狗棒法")); books.put("3", new Book("3", "九阴真经")); books.put("4", new Book("4", "九阳神功")); } // 获取集合的方法 public static HashMap getBooks() { return books; } // 按 id 查找对应书的方法 public static Book findBookById(String id) { return books.get(id); } } /* * Session * 钝化 * 服务器停止时 * 如果你的 session 中保存了对象 * 并且该对象实现了序列化接口 Serializable * 系统会把你保存 session 序列化到服务器的 work 文件夹你的工程下一个文件 * 活化 * 当你重新启动了服务器,系统会重新把钝化的文件进行加载,加载回 session 中 */ public class Book implements Serializable { /** * 序列化 id */ private static final long serialVersionUID = 1L; private String id; private String name; public Book() { super(); } public Book(String id, String name) { super(); this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return id + " " + name; } } public class AddBook extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); // 获取点击是哪本书(获取参数) String id = request.getParameter("id"); Book book = BookUtil.findBookById(id); // 创建一个容器(相当于购物车,保存买的书) // 两种情况:1.已结存过书了;2.没存过 HttpSession session = request.getSession(); ArrayList car = (ArrayList)session.getAttribute("car"); if (car == null) { // 相当于第一次访问,创建容器 car = new ArrayList<>(); } // 把书添加到容器中 car.add(book); // 把容器添加到 session 中 session.setAttribute("car", car); // 显示添加成功 // 1秒后返回商品列表页 response.setHeader("refresh", "2;url=" + request.getContextPath() + "/showallbooks"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

http://blog.csdn.net/huzongnan/article/list

你可能感兴趣的:(Java 之 HttpSession)