1.会话技术
为了实现某一功能,浏览器和服务器之间可能会发生多次的请求和响应,从浏览器访问服务器开始,到最后访问服务器结束为止,期间产生的所有的请求和响应加在一起,称之为一次会话。
2.Session
2.1Session概述
Session是将会话的数据保存在了服务器端。
过程描述:
浏览器向服务器发送请求,将需要保存的数据提交给服务器,服务器收到数据后,检测是否有为浏览器服务的session,如果有直接存入对应的session,如果没有,创建session并保存数据。浏览器再次访问服务器时,服务器直接从该浏览器对应的Session中获取数据,通过这种方式就保存了会话中产生的数据。
2.2Session域
Session的生命周期:
1.创建:
第一次调用request.getSession()方法时创建,该方法如果有session则直接拿来使用,如果没有,则创建
2.销毁:
2.1超时死亡:如果session30分钟(默认)不使用则销毁
可以在web.xml中设置超时时间,单位为分钟
<session-config>
<session-timeout>1</session-timeout>
</session-config>
2.2主动杀死:调用session.invalidate()方法时会立即销毁session
2.3意外身亡:服务器意外关闭,session会立即销毁。服务器正常关闭,session会钝化,服务器再次开启时,session会活化。
作用范围:整个会话
功能:在整个会话范围内共享数据
3.代码示例
如下代码,先访问SessionDemo1(,urlPatterns = "/sessiondemo1"),向Session中存入数据,然后在SessionDemo2中可以获取到刚刚存入的属性值,在调用SessionDemo3,杀死Session,Session被杀死后如果再次访问SessionDemo2,则会报空指针错误,因为此时Session已经被杀死,
SessionDemo1,向Session中存入域属性
@WebServlet(name = "SessionDemo1",urlPatterns = "/sessiondemo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session
HttpSession session = request.getSession();
//向session中存入域属性
session.setAttribute("friend","李四");
session.setAttribute("score",60);
System.out.println("sessiondemo1:"+session.getAttribute("friend"));
}
}
SessionDemo2,从Session中获取域属性
@WebServlet(name = "SessionDemo2",urlPatterns = "/sessiondemo2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session
HttpSession session = request.getSession();
//从session中获取域属性
String friend = (String) session.getAttribute("friend");
int score = (int) session.getAttribute("score");
System.out.println("sessiondemo2:"+friend+"@"+score);
}
}
SessionDemo3,杀死Session
@WebServlet(name = "SessionDemo3",urlPatterns = "/sessiondemo3")
public class SessionDemo3 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//杀死session
request.getSession().invalidate();
}
}
在Session杀死前,debug类SessionDemo的结果如下:
在调用 SessionDemo3杀死Session后,获取的属性已经为null
此时执行debug的放行按钮,前端出现500错误,抛出 java.lang.NullPointerException 异常