目录

前言

1.Cookie经典案例优化

2.Session会话

什么是Session对话?

3.HttpSession接口中的常用方法

4.Session的生命周期

5.案例分析-创建 Session 和获取(id 号并判断是否为新)

 结束语


java 获取session很麻烦_java-ee

前言

我们了解了JavaWeb中的会话和会话技术,了解什么是Cookie,掌握Cookie对象的使用.这篇我们就来进一步学习一下Session会话技术。并且将上一次的Cookie案例进行进一步的优化。

1.Cookie经典案例优化

java 获取session很麻烦_java_02

package cookie.test2;

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 java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

import static java.lang.System.out;

/**
 * @author Sun
 * @version 2021.2
 * @date 2022/5/10 17:41
 */
@WebServlet("/lasttime")
public class LastTimeServlet extends HttpServlet {

    /**
     * 任务:当某个客户端浏览器访问当前Servlet程序时,需要给该客户端浏览器显示它上一次访问本程序的时间
     * 使用客户端的Cookie存储
     * 设计:
     * 1.尝试从客户端浏览器中读取所有Cookie数据
     *     (1)遍历查找所有Cookie数据中,哪一个Cookie对象的name是用来存储“上次访问时间”
     *     a.找到了
     *     取出值并显示
     *     并且更新“上次访问时间”,因为上次访问时间是一个相对的数据,需要更新该数据
     *     b.没找到
     *     在浏览器中显示,你是第一次访问本程序
     *     并且更新“上次访问时间”,因为上次访问时间是一个相对的数据,需要更新该数据
     *     (2)客户端没有Cookie数据
     *     在浏览器中显示,你是第一次访问本程序
     *     并且更新“上次访问时间”,因为上次访问时间是一个相对的数据,需要更新该数据
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //指定服务器输出内容编码方式,以防发生乱码
        resp.setContentType("text/html;charset=utf-8");
        //获取所有的cookie
        Cookie[] cookies=req.getCookies();
        //定义flag 用于判断cookies是否为空
        boolean flag=false;
        //遍历cookie数组
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie:cookies) {
                //获取cookie的名称
                String name=cookie.getName();
                //判断名称是否为LastAssessTime
                if ("LastAssessTime".equals(name)){
                    //该cookie不是第一次访问
                    flag=true;
                    //响应数据
                    //获取cookie中的value时间
                    String value=cookie.getValue();
                    //对Cookie中的value进行url解码
                    String time2= URLDecoder.decode(cookie.getValue(),"utf-8");
                    resp.getWriter().write("上次访问时间"+time2);
                    //设置cookie的value
                    //获取当前时间的字符串,重新设置cookie的值,重新发送cookie
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd号 hh时mm分ss秒");
                    String time= sdf.format(date);

                    String urlTime= URLEncoder.encode(time,"utf-8");


                    cookie.setValue(urlTime);

                    //设置cookie存活时间
                    cookie.setMaxAge(60*60*24*5);//5天
                    //加入当前cookie请求时间
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        if (cookies==null || cookies.length==0 || flag==false){
            //设置cookie的value
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd号 hh时mm分ss秒");
            String time= sdf.format(date);
            String urlTime= URLEncoder.encode(time,"utf-8");
            Cookie cookie=new Cookie("LastAssessTime",urlTime);
            //设置cookie存活时间
            cookie.setMaxAge(60*60*24*5);//5天
            //加入当前cookie请求时间
            resp.addCookie(cookie);
            resp.getWriter().write("欢迎首次访问");

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}

我们使用URL编码使中文字符可以显示出来,同时也需要对它进行URL解码,下面就是解码前和解码后的区别。

解码前 :

URL编码

String urlTime= URLEncoder.encode(time,"utf-8");

                    cookie.setValue(urlTime);

java 获取session很麻烦_数据_03

 解码后:

URL解码

String time2= URLDecoder.decode(cookie.getValue(),"utf-8");
                    resp.getWriter().write("上次访问时间"+time2);

java 获取session很麻烦_java-ee_04

 这就解决了Cookie中不支持中文和空格的问题啦!!!

2.Session会话

什么是Session对话?

1.Session就是一个接口

2.Session就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。

3.每个客户端都有自己的一个Session会话

4.Session会可以将会话数据保存在服务器中。(Cookie是将用户信息保存在各自浏览器中)

3.HttpSession接口中的常用方法

request.getSession()
第一次调用是:创建 Session 会话
之后调用都是:获取前面创建好的 Session 会话对象。

isNew();
判断到底是不是刚创建出来的(新的)
true 表示刚创建
false 表示获取之前创建

每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。
getId() 得到 Session 的会话 id 值。

protected void CreateOrGetSession (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //创建或获取Session会话对象
    HttpSession session = req.getSession();
    //判断当前Session会话是否是新创建出来的
    boolean isNew = session.isNew();
    //获取Session会话的唯一标识 id
    String id = session.getId();

    resp.getWriter().write("得到的Session它的id是:" + id + "<br/>");
    resp.getWriter().write("这个Session是否是新创建的:" + isNew + "<br/>");
}
setAttribute 方法:
/**
 * 往 Session 中保存数据
 */
protected void setAttribute (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getSession().setAttribute("key1","value1");
    resp.getWriter().write("已经往 Session 中保存了数据");
}
getAttribute 方法:
/**
 * 获取 Session 域中的数据
 */
protected void getAttribute (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Object attribute = req.getSession().getAttribute("key1");
    resp.getWriter().write("从 Session 中获得的 key1 的数据是:" + attribute);
}
public void setMaxInactiveInterval(int interval)
 设置 Session 的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。
 值为正数的时候,设定 Session 的超时时长
 负数表示永不超时(极少使用,因为如果不销毁就会一直占用内存空间)public int getMaxInactiveInterval()
 获取 Session 的超时时间public void invalidate()
 让当前 Session 会话马上超时无效

4.Session的生命周期

Session 默认的超时时间长为 30 分钟。
因为在 Tomcat 服务器的配置文件 web.xml 中(D:\JavaWeb\apache_tomcat9\conf)
默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。

java 获取session很麻烦_数据_05

java 获取session很麻烦_java-ee_06

 如果说,你希望你的 web 工程默认的 Session 的超时时长为其他时长,你可以在你自己的 web.xml 配置文件中做 以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。

<!--表示当前 web 工程。创建出来的所有 Session 默认是 50分钟 -->
<session-config>
    <session-timeout>50</session-timeout>
</session-config>

5.案例分析-创建 Session 和获取(id 号并判断是否为新)

package session.test;

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

/**
 * @author Sun
 * @version 2021.2
 * @date 2022/5/10 18:58
 */
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out=resp.getWriter();

        //获取Session对象,使用请求的get方法
        HttpSession session=req.getSession(true);
        //设置发呆时间
        session.setMaxInactiveInterval(50);
        if (session==null){
            out.println("<h2>获取Session失败,我不创建</h2>");
        } else {

            out.println("<h2>Session id:" + session.getId() + "</h2>");
            out.println("<h2>是否是一个新的Session:" + session.isNew() + "</h2>");
            session.invalidate();
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

java 获取session很麻烦_java-ee_07

刷新: 

 

java 获取session很麻烦_java_08

创建和获取(id号、是否为新创建)之后,再点击 刷新 50秒超时销毁,之后立即连续点击Session 的创建和获取(id号、是否为新创建),我们会发现,这个Session是否是新创建的显示一直为:false,但是如果停三秒钟之后再点击,就会发现变为了 true,并且这个Session的id也改变了。
 

java 获取session很麻烦_java_09