- 为什么要使用Session?
- 怎样使用Session?
- Session和Cookie的区别?
1.为什么要使用Session?
Session属于服务器端存储数据,不限制存储的内容,任意类型均可存储。
2.怎样使用Session?
2.1 Session常用方法
用法 | 说明 |
---|---|
HttpSession session = request.getSession() | 获取HttpSession对象 |
Object getAttribute(String name) | 使用HttpSession对象 |
void setAttribute(String name, Object value) | 设置HttpSession对象 |
void removeAttribute(String name) | 删除HttpSession对象 |
2.2 Session完整示例
示例代码
@WebServlet("/session1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession httpSession = req.getSession();
httpSession.setAttribute("msg","hello session");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
@WebServlet("/session2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession httpSession = req.getSession();
System.out.println(httpSession.getAttribute("msg"));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
效果展示
3. Session和Cookie的区别?
- session存储数据在服务器端,Cookie在客户端
- session没有数据大小限制,Cookie有
- session数据安全,Cookie相对于不安全