入门JavaWeb之 Session 篇

Session:

服务器会给每个用户(浏览器)创建一个 Session 对象

一个 Session 独占一个浏览器,只要浏览器没有关闭,这个 Session 就存在

代码如下:

package com.demo.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class Session extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");

        //得到Session
        HttpSession session = req.getSession();

        //给Session中存东西
        session.setAttribute("name","hhh");

        //获取Session的ID
        String id = session.getId();

        //判断Session是否是新创建的
        if (session.isNew()){
            resp.getWriter().write("Session创建,ID:"+id);
        }else {
            resp.getWriter().write("Session已经在服务器存在,ID:"+id);
        }

    }

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

web.xml 注册:

  <servlet>
    <servlet-name>se</servlet-name>
    <servlet-class>com.demo.cookie.Session</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>se</servlet-name>
    <url-pattern>/se</url-pattern>
  </servlet-mapping>

运行后查看结果

应用程序存入 SessionID

请求头存入 SessionID

注销 Session:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        //手动注销Session
        session.invalidate();
    }

进入注销页再进入 SessionID 页,SessionID 改变

还可以设置 Session 默认失效时间

  <!-- 设置Session默认失效时间 -->
  <session-config>
    <!-- 15分钟后Session自动失效,以分钟为单位 -->
    <session-timeout>15</session-timeout>
  </session-config>

Session 与 Cookie 的区别:

1. Cookie 是把用户的数据写给用户的浏览器,浏览器保存,可以保存多个

2. Session 把用户的数据写到用户独占 Session 中,服务器端保存(保存重要的信息,减少服务器资源的浪费)

3. Session 对象由服务器创建

服务器中的 Session 可以存东西,客户端向服务器发起请求,将登记一个 Session

用户拿到的是 SessionID,每个用户唯一

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值