首页 > 代码库 > HttpSession
HttpSession
模拟购物车页面页面
package cn.soldier.session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/* * 模拟购物车页面页面 * */@WebServlet("/sessionDemo1")public class SessionDemo1 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); session.setAttribute("buy", "电视机"); /* * encodeUrl * * 为url构造JSESESSIONID,防止用户禁用cookie后,session失效。 * 第一次访问时encodeUrl会构造JSESESSIONID, * 当判断到用户浏览器没有禁用cookie会关闭构造JSESESSIONID */ String url1 = response.encodeUrl("ServletDemo/sessionDemo1"); String url2 = response.encodeUrl("ServletDemo/sessionDemo2"); out.write("<a href=http://www.mamicode.com/‘" + url1 + "‘>购买</a></br><a href=http://www.mamicode.com/‘" + url2 + "‘>结账</a>"); // 使session失效 /* session.invalidate(); */ } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}
模拟结账页面
package cn.soldier.session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 模拟结账页面 */@WebServlet("/sessionDemo2")public class SessionDemo2 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); String sessionId = session.getId(); //设置cookie 是为了防止浏览器关闭用户丢失Session。 Cookie cookie = new Cookie("JSESESSIONID",sessionId); cookie.setPath("day07"); cookie.setMaxAge(60*30); response.addCookie(cookie); String product = (String) session.getAttribute("buy"); out.write("您购买了" + product+"<br />"); String url1 =response.encodeUrl("ServletDemo/sessionDemo1"); String url2 =response.encodeUrl("ServletDemo/sessionDemo2"); out.write("<a href=http://www.mamicode.com/‘"+url1+"‘>购买</a></br><a href=http://www.mamicode.com/‘"+url2+"‘>结账</a>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }}
HttpSession
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。