首页 > 代码库 > Servlet笔记10--Session
Servlet笔记10--Session
Web编程中的Session:
代码示例:
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpSession; 10 11 public class AccessMySelfSessionServlet extends HttpServlet { 12 13 private static final long serialVersionUID = 1L; 14 15 @Override 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 19 String ip = request.getRemoteAddr(); 20 HttpSession session = request.getSession(); 21 System.out.println(ip + "‘s session = " + session); 22 //向session范围中存储数据 23 session.setAttribute("username", "zhangsan"); 24 } 25 }
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpSession; 10 11 public class GetDataFromSessionServlet extends HttpServlet { 12 13 private static final long serialVersionUID = 1L; 14 15 @Override 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 HttpSession session = request.getSession(); 19 //从session范围中读取数据 20 Object username = session.getAttribute("username"); 21 System.out.println(username); 22 } 23 24 25 }
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpSession; 10 11 public class LogoutServlet extends HttpServlet { 12 13 private static final long serialVersionUID = 1L; 14 15 @Override 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 19 //获取session对象,若没有获取到session对象,则新建session对象 20 // HttpSession session = request.getSession(); 21 22 //获取session对象,若没有获取到session对象,则新建session对象 23 // HttpSession session = request.getSession(true); 24 25 //获取session对象,若没有获取到session对象,则返回null 26 HttpSession session = request.getSession(false); 27 if(session != null){ 28 //销毁session 29 session.invalidate(); 30 } 31 } 32 33 34 }
Servlet笔记10--Session
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。