时间:2024-5-10 作者:老大夫 分类: JavaWeb
Session与cookie相比 Session是存储在服务端的数据,使用Session 一定要配合cookie使用
session是不能自己new的,只能 request.getSession 放入参数 setAttribute(“usernmae”,object)
再用session 用 getAttribute(“username”)获取参数
package com.atguigu.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/servlet1")
public class Servlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收请求中的username参数
String username = req.getParameter("username");
//获得session对象
HttpSession session = req.getSession();
//判断请求中是否有特殊的cookie JSESSIONID 值 **** ****
//有,
// 根据JESSIONID去找对应的session对象
// 1. 找到了
//返回之前的session
// 2. 没找到
//创建一个新的session返回 自动resp中存放一个JSESSIONID的cookie
//没有,则创建一个新的session返回 自动resp中存放一个JSESSIONID的cookie
System.out.println(session.getId());
System.out.println(session.isNew());
//将username存入session
session.setAttribute("username",username);
//客户端响应信息
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("成功");
}
}
package com.atguigu.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/servlet2")
public class Servlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
System.out.println(session.isNew());
//读取对象
String username = (String) session.getAttribute("username");
System.out.println("servlet2 get username: "+username);
}
}
推荐阅读: