JAVAEE HttpSession

HttpSession

昨天博客已经提到了会话有两个技术 第一种是已经解释的cookie 第二种就是今天要谈论的session
session 是一个服务端技术
服务器会为每一个用户创建一个独立的HttpSession
HttpSession 原理:
1. 当用户第一次访问servlet 服务器端会给该用户创建一个独立的session
2. 并且生成一个sessionID
3. 这个SessID 在响应浏览器的时候 会被装进cookie中 从而被保存到浏览器中
4. 当用户再一次访问servlet的时候 请求中会携带着 cookie中的sessionID 来访问
5. 服务器会根据这个sessionID 来查看是否有对应的sessionID 对象 有就取出使用 否则就创建新的session(相当于用户第一次访问)
因此session 和 之前的 request 和 context 很像 是一个 域对象 他们的范围大小是 Context 域 > Session 域 > request 域
session域特点是 session域 只要会话不结束 就会存在 但是 Session有默认的存活时间 30分钟

创建第一个session

// Demo01.java
public class Demo01 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);
        System.out.println(session.getId());

    }

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

}
// Demo02.java
public class Demo02 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);
    }
}

简单购物车问题

ShowAllBooks.java
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");
        PrintWriter out = response.getWriter();
        HashMap books = Bookutil.getBooks();

        Set keySet = books.keySet();
        for (String string : keySet) {
            Book book = books.get(string);
            out.write("");

        }
        // 添加查看购物车连接
        out.write("");  
        // 设置session的有效时间
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(10);
    }

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


Book.java
public class Book implements Serializable{

    /**
     * Session 
     * 钝化 服务器停止 如果你在session中保存了对象 并且该对象实现了序列化接口Serializable
     *      系统会把你保存的session 序列化到 服务器的work文件夹 work文件夹下
     * 
     * 活化
     *  当你重新启动服务器 系统会重新把钝化下的文件加载回session中
     */
    private static final long serialVersionUID = 1L;
    private String id;
    private String name;

    public Book() {
        // TODO Auto-generated constructor stub
    }

    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 "Book [id=" + id + ", name=" + name + "]";
    }
}


Bookutil.java
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", "JAVA编程思想"));
    }

    // 获取集合的方法
    public static HashMap getBooks() {


        return books;
    }
    // 按id 查找对应书的方法
    public static Book findBookById(String id) {
        return books.get(id);
    }
}


AddBook.java
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");
        HttpSession session = request.getSession();
        // 获取点击的是哪本书
        Book books = Bookutil.findBookById(id);
        // 创建一个容器       
        // 把这个容器添加到session中
        // 两种情况 1. 书已经添加 2. 书没有添加
        ArrayList book = (ArrayList) session.getAttribute("id");
        if (book == null) {
            // 相当于 第一次访问 创建容器
            book = new ArrayList<>(); 
        }
        // 把书添加到容器中
        book.add(books);
        // 把容器添加到session中
        session.setAttribute("id", book);
        // 显示添加成功 1秒后返回商品列表
        response.getWriter().write("添加成功 1秒钟后跳转");
        response.setHeader("refresh", "1;url=/sh-web-servlet04/showallbooks");
    }

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

}

ShowBook.java

public class ShowBook extends HttpServlet {

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

        HttpSession session = request.getSession();
        ArrayList list = (ArrayList) session.getAttribute("id");
        if (list != null) {
            for (Book book : list) {
                response.getWriter().write(book.getName() + "
"
); } } else { response.getWriter().write("暂无商品" + "
"
); response.setHeader("refresh", "1;url=/sh-web-servlet04/showallbooks"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

你可能感兴趣的:(java)