【JSP】Session总结

Session

Session是服务器端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的session对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务。

1、Session和Cookie的区别

  • Cookie是把用户的数据写给用户的浏览器。
  • Session技术把用户的数据写到用户独占的session中。
  • Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象。
2、HttpSession

1)HttpSession:在服务器端保持 HTTP 状态信息的方案,和其对应的是Cookie 。

2)产生HttpSession对象的过程:当程序需要为某个客户端的请求创建一个session时,服务器首先检查这个客户端的请求里是否包含了一个session标识(即sessionId),如果已经包含一个sessionId则说明以前已经为此客户创建过session,服务器就按照session id把这个session检索出来使用(如果检索不到,可能会新建一个,这种情况可能出现在服务端已经删除了该用户对应的session对象,但用户人为地在请求的URL后面附加上一个JSESSION的参数)。如果客户请求不包含sessionId,则为此客户创建一个session并且生成一个与此session相关联的sessionId,这个session id将在本次响应中返回给客户端保存。

3)使用Cookie来跟踪Session:session通过SessionID来区分不同的客户, session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,这称之为session cookie,以区别persistent cookies(也就是我们通常所说的cookie),session cookie是存储于浏览器内存中的,并不是写到硬盘上的。

3、HttpSession的生命周期

1)创建一个HttpSession对象:一个常见的错误是以为session在有客户端访问时就被创建(若第一次访问某Web应用的一个JSP页面,且该页面的page指定的Session属性为false,此时就不会产生Session对象)。
①某server端程序(如Servlet)调用HttpServletRequest.getSession(true) 或者 HttpServletRequest.getSession()这样的语句时才会被创建。
②若第一次访问某Web应用的一个JSP页面,且该页面的page指定的Session属性为true,则服务器会自动为该页面分配一个HttpSession对象。

2)销毁HttpSession对象:
A.程序调用HttpSession.invalidate()
B.距离上一次收到客户端发送的session id时间间隔超过了session的最大有效时间
C.服务器进程被停止
注意:关闭浏览器只会使存储在客户端浏览器内存中的session cookie失效,不会使服务器端的session对象失效。*

4、HttpSession的相关API

1)获取Session对象:request.getSession()、request.getSession(boolean create)
2)属性相关的:setAttribute、getAttribute、removeAttribute
3)使HttpSession失效:HttpSession.invalidate()
4)设置最大时效:settMaxInactiveInterval()

5、URL重写

1)Servlet规范中引入了一种补充的会话管理机制,它允许不支持Cookie(或禁用Cookie)的浏览器也可以与WEB服务器保持连续的会话
2)将会话标识号以参数形式附加在超链接的URL地址后面的技术称为URL重写。
3)代码:encodeURL方法 、encodeRedirectURL方法

    <a href="<%= response.encodeURL("login.jsp") %>">重新登录</a>   
    <a href="<%= response.encodeURL("logout.jsp") %>">注销</a>

6、运用Session模拟购物订单

顾客信息类(javabean)

package com.lhk.shoppingServlet;

public class Customer {
    private String name;
    private String address;
    private String information;
    private String cardType;
    private String cardNum;

    public Customer(String name, String address, String information, String cardType, String cardNum) {
        super();
        this.name = name;
        this.address = address;
        this.information = information;
        this.cardType = cardType;
        this.cardNum = cardNum;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getInformation() {
        return information;
    }
    public void setInformation(String information) {
        this.information = information;
    }
    public String getCardType() {
        return cardType;
    }
    public void setCardType(String cardType) {
        this.cardType = cardType;
    }
    public String getCardNum() {
        return cardNum;
    }
    public void setCardNum(String cardNum) {
        this.cardNum = cardNum;
    }
}

顾客选择要购买的书籍

【step-1.jsp】
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>Step1:请选择要购买的书籍</h2>
    <form action="<%=request.getContextPath() %>/step1Servlet" method="post">
        <table cellpadding="10" cellspacing="0" border="1">
            <tr>
                <td>书名</td>
                <td>购买</td>
            </tr>
            <tr>
                <td>Java</td>
                <td><input type="checkbox" name="book" value="Java"></td>
            </tr>
            <tr>
                <td>Oracle</td>
                <td><input type="checkbox" name="book" value="Oracle"></td>
            </tr>
            <tr>
                <td>Struts</td>
                <td><input type="checkbox" name="book" value="Struts"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

将顾客购买的书籍保存到Session中

【Step1Servlet.java】package com.lhk.shoppingServlet;

import java.io.IOException;
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;

/**
 * Servlet implementation class Step1Servlet
 */
@WebServlet("/step1Servlet")
public class Step1Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        //1. 获取选中的图书的信息
        String[] bookNames = request.getParameterValues("book");

        //2. 把图书信息放入到 HttpSession 中
        session.setAttribute("bookNames", bookNames);

        //3. 重定向页面到 shopping/step-2.jsp  绝对路径
        response.sendRedirect(request.getContextPath()+"/shopping/step-2.jsp");
    }
}

顾客输入个人基本信息

【step-2.jsp】
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>step2:请输入寄货地址与信用卡信息</h2>
    <form action="<%=request.getContextPath() %>/step2Servlet" method="post">
        <table cellpadding="10" cellspacing="0" border="1">
            <tr>
                <td colspan="2">基本信息</td>
            </tr>
            <tr>
                <td>姓名</td>
                <td><input type="text" name="name"/></td>
            </tr>
            <tr>
                <td>寄送地址</td>
                <td><input type="text" name="address"/></td>
            </tr>
            <tr>
                <td>信用卡信息</td>
                <td><input type="text" name="information"/></td>
            </tr>
            <tr>
                <td >种类</td>
                <td>
                    <input type="radio" name="cardType" value="Visa" />Visa
                    <input type="radio" name="cardType" value="Master" />Master
                </td>
            </tr>
            <tr>
                <td>卡号</td>
                <td><input type="text" name="cardNum"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

将顾客的基本信息保存到Session

【Step2Servlet.java】
package com.lhk.shoppingServlet;

import java.io.IOException;
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;

/**
 * Servlet implementation class Step2Servlet
 */
@WebServlet("/step2Servlet")
public class Step2Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();

        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String information = request.getParameter("information");
        String cardNum = request.getParameter("cardNum");
        String cardType = request.getParameter("cardType");

        Customer customer = new Customer(name, address, information, cardType, cardNum);

        session.setAttribute("customer", customer);

        response.sendRedirect(request.getContextPath()+"/shopping/confirm.jsp");
    }
}

从Session中读出订单信息

【confirm.jsp】
<%@page import="com.lhk.shoppingServlet.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <%
        Customer customer = (Customer)session.getAttribute("customer");
        String[] bookNames = (String[])session.getAttribute("bookNames");
    %>


    <h2>step3:订单确认</h2>
        <table cellpadding="10" cellspacing="0" border="1">
            <tr>
                <td>顾客姓名</td>
                <td><%=customer.getName() %></td>
            </tr>
            <tr>
                <td>寄送地址</td>
                <td><%=customer.getAddress() %></td>
            </tr>
            <tr>
                <td>信用卡信息</td>
                <td><%=customer.getInformation() %></td>
            </tr>
            <tr>
                <td>信用卡类型</td>
                <td><%=customer.getCardType() %></td>
            </tr>
            <tr>
                <td>卡号</td>
                <td><%=customer.getCardNum() %></td>
            </tr>
            <tr>
                <td>订货项目</td>
                <td>
                    <%for(String book:bookNames) {
                        out.print(book+"</br>");
                    }%>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"/></td>
            </tr>
        </table>
</body>
</html>

这里写图片描述

  • 11
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值