Session
- 概念:服务器端会话技术,再一次会话的多次请求间共享数据,将数据保存再服务器端的对象中。HTTPSession
- 快速入门:
- 获取HttpSession对象
- HttpSession session = request.getSession();
- 使用HttpSession对象:
- Object getAttribute(String name)
- void setAttribute(String name,Object value)
- void removeAttribute(String name)
package com.ailyt.session;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(value = "/sessionStudy01")
public class SessionStudy01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("html/text;charset=utf-8");
//使用Session共享数据
//1.获取Session
HttpSession session = request.getSession();
//2.存储数据
session.setAttribute("msg","hello session");
}
}
package com.ailyt.session;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(value = "/sessionStudy02")
public class SessionStudy02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用Session获取数据
//获取Session
HttpSession session = request.getSession();
//获取数据
Object value1 = session.getAttribute("msg");
System.out.println("-->" + value1);
}
}
Session原理分析
- Session的实现是依赖于Cookie的