往session中存储信息
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取session对象
HttpSession session = req.getSession();
//往session里存数据
session.setAttribute("name",new Person("gsy",1));
//获取session的ID
String sessionId = session.getId();
//判断session是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID为:"+ sessionId);
}else{
resp.getWriter().write("session在服务器中存在了,ID为:"+sessionId);
}
//创建session的时候浏览器做了什么
//在这里浏览器创建了一个将创建的session的ID通过cookie来传递
//就是说sessionID也是由cookie来传递的
Cookie cookie = new Cookie("name","123");
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
session中可以存放Object类型的数据,所以我们可以在session中存放对象
cookie中只能存放String类型的数据
获取session中的对象属性
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//首先解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
注销session
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销session
session.invalidate();
//还可以在xml文件中设置session的默认失效时间
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
在xml文件中设置了session的默认失效时间
<!--
设置session的过期时间,以分钟为单位
-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
cookie和session的区别:
1.cookie是把用户的数据存在客户端的浏览器(可以保存多个)可以将session的sessionid传递给客户端
2.session是把数据放在服务端进行保存,用来存储一些重要的数据
3.session对象由服务端创建
4.服务端给客户端一个cookie,客户端访问的时候是带着cookie进行访问的
5.客户端请求服务端的时候,服务端登记一个sessionid给客户端,客户端通过sessionid来获取存在session中的数据
6.如果用户很多,想要访问所有用户都能共享的数据时我们需要用servletContext(ApplicationContext)