zoukankan      html  css  js  c++  java
  • session原理解析

    cookie机制采用的是在客户端保持状态的方案,而session机制采用的是在服务器端保持状态的方案;

    由于采用服务器端保持状态的方案在客户端也需要保存一个标识,所以session机制可能需要借助于cookie机制来达到保存标识的目的。

    session实现购物车案例

    Book.java 

    javabean  

    package car;
    
    public class Book {
    
        private String id;
        private String bookName;
        private String author;
        private int price;
        private String description;
        private int count;
        
        
        
        public Book(String id, String bookName, String author, int price,
                String description) {
            this.id = id;
            this.bookName = bookName;
            this.author = author;
            this.price = price;
            this.description = description;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getBookName() {
            return bookName;
        }
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public int getPrice() {
            return price;
        }
        public void setPrice(int price) {
            this.price = price;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public int getCount() {
            return count;
        }
        public void setCount(int count) {
            this.count = count;
        }
        @Override
        public String toString() {
            return "Book [id=" + id + ", bookName=" + bookName + ", author="
                    + author + ", price=" + price + ", description=" + description + "]";
        }
        
        
        
    }

    BookUtils.java

     用来存取数据

    package utils;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import car.Book;
    
    public class BookUtils {
    
        private static Map<String,Book> map = new HashMap<String,Book>();
        
        static{
            map.put("1", new Book("1","三年中考五年模拟","李刚",100,"中学生的噩梦"));
            map.put("2", new Book("2","最后一个硬汉","郎咸平",1000,"666的经济学"));
            map.put("3", new Book("3","我的奋斗","李刚",1003,"中学生的噩梦"));
            map.put("4", new Book("4","三年中考五年模拟444","李刚4",400,"中学生的噩梦4"));
            map.put("5", new Book("5","三年中考五年模拟555","5李刚",500,"中学生的噩梦5"));
            map.put("6", new Book("6","666三年中考五年模拟","李6刚",600,"中学生的噩梦6"));
        }
        //获取所有的书
        public static Map<String,Book> getAllBook(){
            return map;
        }
        //根据书的id获取某一本书
        public static Book getBookById(String id){
            return map.get(id);
        }
    }

    ShowAllBookServlet.java

    显示所有的书籍信息,从map中拿取信息

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import utils.BookUtils;
    import car.Book;
    
    public class ShowAllBookServlet extends HttpServlet {
    
        /**
         * 1.显示所有书的信息
         * 2.提供一个购物车的链接
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("书库:<br><br>");
            //1.显示所有的书
            Map<String, Book> map = BookUtils.getAllBook();
            //显示获取到的书
            for (Map.Entry<String, Book> entry : map.entrySet()) {
                //拿到每一本的id
                String id = entry.getKey();
                //拿到每一本书
                Book book = entry.getValue();
                //输出书的内容
                out.write("" + book.getBookName() +"" +"<a href=' "+ request.getContextPath() +"/servlet/ShowBookDetailServlet?id=" + id + " '>显示详细信息<a><br><br>");
            }
            out.write("<br><hr>");
            //提供查看购物车的链接
            out.write("<a href=' " + request.getContextPath() + "/servlet/CarServlet '>查看购物车</a>");
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doGet(request, response);
        }
    
    }

    ShowBookDetailServlet.java

    显示书籍的详细信息,并可以将书籍加入购物车

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import utils.BookUtils;
    import car.Book;
    
    public class ShowBookDetailServlet extends HttpServlet {
    
        /**
         * 1.显示书的详细信息
         * 2.提供购物车的链接
         * 3.返回继续浏览的链接
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            //显示书的详细信息
            String id = request.getParameter("id");
            Book book = BookUtils.getBookById(id);
            
            out.write(book + "<a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '> 返回主页继续浏览 </a>" + "&nbsp;&nbsp;<a href=' " + request.getContextPath() + "/servlet/BuyServlet?id=" + id + " '>放入购物车</a>");
            
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doGet(request, response);
        }
    
    }

    BuyServlet.java

    处理提交的数据,将数据放入session中

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    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 utils.BookUtils;
    import car.Book;
    
    public class BuyServlet extends HttpServlet {
    
        /**
         * 将购买的书放入购物车 
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            
            //获取页面传递的id
            String id = request.getParameter("id");
            //根据id找到对象
            Book book = BookUtils.getBookById(id);
            //将书存入session中
            HttpSession session = request.getSession();
            //将书放到session的一个集合中
            List<Book> list = (List<Book>) session.getAttribute("carlist");
            
            if(list == null){
                //说明是第一次加入购物车
                list = new ArrayList<Book>();
                //将·书放入
                book.setCount(1);
                list.add(book);
                //将list放入session
                session.setAttribute("carlist", list);
            }else{
                //说明购物车已经有了东西了
                //判断是否购买过书了
                int index = list.indexOf(book);
                if(index == -1){
                    //没有
                    book.setCount(1);
                    list.add(book);
                }else{
                    //说明已经买过一次了
                    Book b = list.get(index);
                    b.setCount(b.getCount() + 1);
                }
                //提醒用户,书已经放入了
                out.write(book.getBookName() + "已经加入购物车,4秒后转向主页 <a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '>回到主页</a>");
                response.setHeader("Refresh", "4;url=" + request.getContextPath() + "/servlet/ShowAllBookServlet");
            }
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doGet(request, response);
        }
    
    }

    CarServlet.java  存放购物车的信息

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    
    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 car.Book;
    
    public class CarServlet extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            
            out.write("欢迎来到购物车<br>");
            
            HttpSession session = request.getSession();
            if(session.isNew()){
                //直接返回主页面
                response.sendRedirect(request.getContextPath() + "/servlet/ShowAllBookServlet");
                return;
            }
            
            //先从session拿到购物车
            List<Book> list = (List<Book>) session.getAttribute("carlist");
            //如果直接过来的,则让他回去
            if(list == null){
                //首次访问
                out.write("您还没有购买任何东西,2秒后返回主页");
                response.setHeader("Refresh", "2;url=" + request.getContextPath() + "/servlet/ShowAllBookServlet");
                return;
            }
            //说明有数
            out.write("您购买的书籍如下:<br>");
            out.write("书名	数量	总价格<br>");
            for (int i = 0; i< list.size(); i++) {
                Book b = list.get(i);
                out.write(b.getBookName() + "	" + b.getCount() + "	" + b.getPrice() * b.getCount() + "<br>");
            }
            out.write("<br><br><a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '>返回主页</a>");
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doGet(request, response);
        }
    
    }

    可以了。

  • 相关阅读:
    linux执行命令并获取结果(system)
    awk----基本用法
    shell用法总结
    autoit(au3)使用说明
    博客搜集
    vi常用快捷键总结
    python简单学------------程序传参数,列表推导式,set、list、tuple 转换
    python简单学------------模块
    python简单学------------python面向对象(3)
    python简单学------------python面向对象(2)
  • 原文地址:https://www.cnblogs.com/taiguyiba/p/6145582.html
Copyright © 2011-2022 走看看