JavaWeb16.5【Cookie&Session:Session原理、快速入门】
1 package com.haifei.session; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 import java.io.IOException; 10 11 /** 12 * session快速入门 13 */ 14 @WebServlet("/SessionDemo1") 15 public class SessionDemo1 extends HttpServlet { 16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 //使用session共享数据 18 19 //1 获取session对象 20 HttpSession session = request.getSession(); 21 //2 存储数据 22 session.setAttribute("msg", "hello session"); 23 } 24 25 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 26 this.doPost(request, response); 27 } 28 }
1 package com.haifei.session; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 import java.io.IOException; 10 11 /** 12 * session快速入门 13 */ 14 @WebServlet("/SessionDemo2") 15 public class SessionDemo2 extends HttpServlet { 16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 //使用session获取数据 18 19 //1 获取session对象 20 HttpSession session = request.getSession(); 21 //2 获取数据 22 Object msg = session.getAttribute("msg"); 23 System.out.println(msg); 24 25 //一次会话,两次/多次请求间的数据共享(两者之间并没有发生资源跳转)。 26 /* 27 http://localhost:8080/day16/SessionDemo1 28 http://localhost:8080/day16/SessionDemo2 29 30 hello session 31 */ 32 33 /* 34 重启浏览器 35 http://localhost:8080/day16/SessionDemo2 36 37 null 38 */ 39 } 40 41 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 42 this.doPost(request, response); 43 } 44 }