标签:session
HttpSession:在服务器中,为浏览器创建独一无二的内存空间,在其中保存会话相关的信息。实验:使用session完成防止表单重复提交:当提供表单页面时,在表单中隐藏一个随机数值,并且将该随机数保存到session中,当表单提交时,检查提交上来到随机数与session中的随机数是否相同,如果相同则允许注册,注册后立即删除session中的随机数,如果不同则认为是表单的重复提交。
实验:实现购买与付账的功能
1.建立一个jsp实现到BuyServlet&PayServlet的超链接并带一个参数过来
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv=" pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <a href="<%=request.getContextPath()%>/servlet/BuyServlet?prod=冰箱">购买冰箱</a> <a href="<%=request.getContextPath()%>/servlet/BuyServlet?prod=空调">购买空调</a> <a href="<%=request.getContextPath()%>/servlet/PayServlet">付账</a> </body> </html>运行界面:
2.在BuyServlet实现通过request.getParamer()的方式获取参数,然后将这个参数设置到session域对象中。下面的设置Cookie的代码是为了实现即时关闭了浏览器(默认是浏览器关闭,cookie死亡,即session丢失)也可以向浏览器写数据。从而关闭了浏览器也可以实现付款(知道是买的那个不会报NULl)
package cn.itheima.session; import java.io.IOException; import javax.servlet.ServletException; 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; public class BuyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决中文乱码问题get提交方式 //1.获取参数 String prod=request.getParameter("prod"); prod = new String(prod.getBytes("iso8859-1"),"utf-8"); //2.放到session域中 HttpSession session = request.getSession(); session.setAttribute("prod", prod); //3.重写Cookie重新设置JSESSIONID的声明周期 Cookie c=new Cookie("JSESSIONID", session.getId()); c.setPath(request.getContextPath()); c.setMaxAge(1800); response.addCookie(c); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }点击购买
package cn.itheima.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //1.获取session String prod = (String) request.getSession().getAttribute("prod"); response.getWriter().write("您购买的是价值9999元的"+prod); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }运行结果:
大家可以尝试关闭浏览器....也能实现付款的功能!
黑马day05 session&重新设置JSESSIONID的生命周期
标签:session
原文地址:http://blog.csdn.net/u014010769/article/details/46564829