Servlet第六篇【Session】
Session的基本使用
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("name","zhangsan");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object name = req.getSession().getAttribute("name");
resp.getWriter().write("session:"+(String)name);
}
Session常用方法
一个用户一个Session对象
resq.getSession():如果对应的用户没有Session则会创建一个Session,如果有,则获取Session
resq.getSession(false):获取Session,如果没有Session,会报错
session.invalidate(): 使Session无效
session.setMaxInactiveInterval(10) 设置session有效期10秒
Session的过期时间
- config/web.xml,设置所有web应用的session过期时间
<!--设置过期时间为10分钟-->
<session-config>
<session-timeout>10</session-timeoout>
</session-config>
- WEB-INF/web.xml,设置单个web应用的session过期时间,优先级高于config/web.xml,默认为30分钟过期
<session-config>
<session-timeout>10</session-timeoout>
</session-config>
- setMaxInactiveInterval()方法
//设置session有效期10秒
ttpSession session = req.getSession();
session.setMaxInactiveInterval(10)
JSESSIONID
-
第一次访问服务器且创建Session则会响应一个JSESSIONID的Cookie(临时的Cookie,不会存储到磁盘)
-
之后请求会带着这个Cookie(服务器不在响应JSESSIONID)

禁用Cookie如何获取JSESSIONID?
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("name","zhangsan");
resp.sendRedirect(resp.encodeURL("/b"));
//resp.sendRedirect(resp.encodeRedirectURL("/b"));
}
URL地址重写原理:服务器转发时将JSESSIONID放在地址栏中

浙公网安备 33010602011771号