javaweb学习15:Session(重点)
作者:互联网
javaweb学习15:Session(重点)
-
Session:
-
服务器会给每一个用户(浏览器)创建一个Session对象;
-
一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
-
-
Session和Cookie的区别:
-
Cookie:把用户的数据写给用户的浏览器;浏览器保存;(可以保存多个)
-
Session:把用户的数据写到用户独占的Session中,服务器端保存;(保存重要信息,减少服务器资源的浪费)
-
Session对象由服务器创建;
-
-
使用场景:
-
保存登录用户的信息;
-
保存购物车的信息;
-
在整个网站中经常会使用的数据,我们将它保存在Session中;
-
-
代码案例:创建Session信息
/**
* Session
*/
public class SessionDemo01 extends HttpServlet {
@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.setAttribute("name",new Person("张三",1));
//获取session的ID
String id=session.getId();
//判断session是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,id为:"+id);
}else{
resp.getWriter().write("session已经在服务器中存在了");
}
//Session创建的时候做了什么事情:
/*Cookie cookie = new Cookie("JSESSIOONID",id);
resp.addCookie(cookie);*/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
-
代码案例:获取Session信息;
public class SessionDemo02 extends HttpServlet {
@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");
resp.getWriter().write(person.toString());
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
-
代码案例:注销Session
public class SessionServlet03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//得到session
HttpSession session = req.getSession();
session.removeAttribute("name");//取消session
session.invalidate();//手动注销session
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
-
代码案例:会话自动过期:以分钟为单位
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!--设置Session默认注销时间-->
<session-config>
<!--1分钟后,session自动失效;以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
</web-app>
标签:15,javaweb,ServletException,Session,resp,req,session,void 来源: https://www.cnblogs.com/xiangcai0522/p/16062747.html