1 package cn.itcast.cookie; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.Cookie; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import javax.servlet.http.HttpSession; 12 13 public class SessionDemo extends HttpServlet { 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 HttpSession session = request.getSession(); 19 20 String sessionid = session.getId(); 21 Cookie cookie = new Cookie("JSESSIONID", sessionid); 22 cookie.setPath("/ServletDemo"); 23 cookie.setMaxAge(30 * 60); 24 response.addCookie(cookie); 25 session.setAttribute("name", "洗衣机"); 26 27 } 28 29 public void doPost(HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException { 31 32 } 33 34 }
1 package cn.itcast.cookie; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import javax.servlet.http.HttpSession; 11 12 public class SessionDemo2 extends HttpServlet { 13 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 response.setCharacterEncoding("UTF-8"); 19 response.setContentType("text/html;charset=UTF-8"); 20 PrintWriter out = response.getWriter(); 21 22 HttpSession session = request.getSession(); 23 String product = (String) session.getAttribute("name"); 24 25 out.print("您购买的商品是:"+product); 26 27 } 28 29 30 public void doPost(HttpServletRequest request, HttpServletResponse response) 31 throws ServletException, IOException { 32 33 34 } 35 36 }
时间: 2024-12-14 03:43:10