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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!