【Java寒假打卡】JavaWeb-Session

概述

在这里插入图片描述

常用的方法

在这里插入图片描述

HttpSession的获取

在这里插入图片描述

HttpSession的使用

在这里插入图片描述

  • 在第一个Servlet中获取请求的用户名
  • 获取HttpSession对象
  • 将用户名设置到共享数据中
  • 在第二个Servlet中获取HttpSession对象
  • 获取共享数据用户名
  • 将获取到的用户名响应给客户端浏览器

Servlet1

package com.hfut.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的用户名
        String username = req.getParameter("username");
        // 获取httpsession对象
        HttpSession session = req.getSession();
        // 将用户名信息添加到共享数据中
        session.setAttribute("username",username);
    }

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

    }
}


Servlet2

package com.hfut.servlet;

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 Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的用户名
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");

        // 将用户名相应给浏览器
        resp.getWriter().write(username + "");
        // 那么访问servlet2资源的时候 浏览器就会打印username信息
    }

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

    }
}


在这里插入图片描述

以上两个servlet拿到的session对象是同一个,保证共享数据资源也是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少写代码少看论文多多睡觉

求打赏,求关注,求点赞

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值