Session:服务端的会话跟踪技术,将数据保存到服务端
JavaEE提供HttpSession接口,来实现一次会话的多次请求间数据共享功能
使用:
①获取Session对象
HttpSession session = request.getSession();
②Session对象功能
void setAttribute(String name,Object o);//存储数据到session域中
Object getAttribute(String name):根据key获取值
void removeAttribute(String name):根据key,删除该键值对
package test.SessionTest;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/ServletSession")
public class ServletSession extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Session对象
HttpSession session = request.getSession();
//存储数据
session.setAttribute("username","zs");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package test.SessionTest;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/ServletSession1")
public class ServletSession1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取数据
HttpSession session = request.getSession();
//获取值
Object username = session.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
网友评论