[Servlet&JSP] HttpSession会话管理

来源:互联网 发布:网络舆情的监测技术 编辑:程序博客网 时间:2024/04/29 04:43

我们可以将会话期间必须共享的资料保存在HttpSession中,使之成为属性。如果用户关掉浏览器接受Cookie的功能,HttpSession也可以改用URL重写的方式继续其会话管理功能。

HttpSession的使用

在Servlet/JSP中,如果要进行会话管理,可以使用HttpServletRequest的getSession()方法取得HttpSession对象。语句如下:

HttpSession session = request.getSession();

getSession()方法有两个版本,另一个版本可以传入布尔值,默认为true,表示若尚未存在HttpSession实例,则直接建立一个新的对象;若传入为false,表示若尚未存在HttpSession实例,则直接返回null。

HttpSession上最常用的方法时setAttribute()与getAttribute(),可以在对象中设置和取得属性。默认在关闭浏览器前,所取得的HttpSession都是形同的实例。如果想要在此次会话期间直接让目前的HttpSession失效,则可以执行HttpSession的invalidate()方法。一个使用的时机就是实现注销机制。一个示例如下:

Login.java:

@WebServlet("/login.do")public class Login extends HttpServlet{    protected void processRequest(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        String username = request.getParameter("username");        String password = request.getParameter("password");        if ("abc".equals(username) && "123".equals(password)) {            request.getSession().setAttribute("login", username);            request.getRequestDispatcher("user.jsp")                .forward(request, response);        } else {            response.sendRedirect("login.html");        }    }    protected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        processRequest(request, response);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        processRequest(request, response);    }}

在登录时,如果用户名与密码正确,就会取得HttpSession并设置一个login属性,用以代表用户完成登录的动作。对于其他的Servlet/JSP,如果可以从HttpSession取得login属性,基本就可以确定是个已登录的用户,这类用来识别用户是否登录的属性,通常称为登录字符(Login Token)。在上例中,登录成功后会转发到用户界面。

User.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>    <c:choose>        <c:when test="${sessionScope.login == null}">            <jsp:include page="login.html" />        </c:when>        <c:otherwise>            <h1>Welcome! ${sessionScope.login}!</h1>            <a href="logout.do">Sign out</a>        </c:otherwise>    </c:choose></body></html>

Login.html

<body>    <form action="login.do" method="post">        username:<input type="text" name="username" /><br />        password:<input type="password" name="password" /><br />        <input type="submit" value="Sign in" />    </form></body>

Logout.java:

@WebServlet("/logout.do")public class Logout extends HttpServlet{    protected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        request.getSession().invalidate();        response.sendRedirect("login.html");    }}

指定HttpSession的invalidate()之后,容器就会销毁并回收HttpSession对象。如果再次执行HttpServletRequest的getSession(),则说的取得的HttpSession就是另外一个新的对象了。

HttpSession会话管理原理

当执行HttpServletRequest的getSession()时,web容器会建立HttpSession对象,每个HttpSession都会有一个特殊的ID,称之为Session ID。可以执行HttpSession的getID()可以取得Session ID。这个Session ID默认会使用Cookie将其存放至浏览器。在Tomcat中,Cookie的名称是JSESSIONID,数字则是getID()所取得的Session ID。

每个HttpSession都有个特殊的Session ID,当浏览器请求应用程序时,会将Cookie中存放的Session ID一并发送给应用程序,web容器根据Session ID来取出对应的HttpSession对象,如此就可以取得各个浏览器的会话数据。

所以使用HttpSession来进行会话管理时,设置为属性的数据是保存在服务器端的,而Session ID默认使用Cookie存放于浏览器中。web容器储存Session ID的Cookie被设置为关闭则浏览器就会失效,重新打开浏览器请求应用程序时,通过getSession()所取得的是新的HttpSession对象。

由于HttpSession会占用内存空间,所以HttpSession得属性中尽量不要保存耗资源的大型对象,必要时可将属性移除,或者不需使用HttpSession时,执行invalidate()让HttpSession失效。

关闭浏览器时会马上失效的是浏览器上的Cookie,而不是HttpSession。

可以执行HttpSession的setMaxInactiveInterval()方法,设置浏览器在多久没有请求应用程序的情况下,HttpSession就会自动失效,设置的单位是”秒”。也可以在web.xml中设置HttpSession默认的失效时间,但要注意的时,这里设置的时间单位是”分钟”。例如:

<web-app ...>    <session-config>        <session-timeout>30</session-timeout>    </session-config></web-app>

保存Session ID的Cookie被设置为关闭浏览器就失效。关闭浏览器后若希望保存信息,必须通过自行操作Cookie来达成,例如完成自动登录机制。

HttpSession与URL重写

如果在用户禁用Cookie的情况下,仍打算运用HttpSession来进行会话管理,那么可以搭配URL重写的方式,向浏览器响应一段超链接,超链接URL后附加Session ID,当用户点击超链接时,则将Session ID以GET请求方式发送给web应用程序。

如果要使用URL重写的方式来发送Session ID,则可以使用HttpServletRequest的encodeURL()协助产生所需的URL重写。当容器尝试取得HttpSession实例时,若可以从HTTP请求中取得带有Session ID的Cookie,encodeURL()会将设置给它的URL原封不动的输出;若无法从HTTP请求中取得带有Session ID的Cookie(通常是浏览器禁用Cookie的情况),encodeURL()会自动产生带有Session ID的URL重写。

如果有执行encdeURL(),在浏览器第一次请求网站时,容器并不知道浏览器是否禁用Cookie,所以容器的做法是Cookie(发送set-cookie标头)与URL重写都做,因此若Servlet有以下语句,无论浏览器是否禁用Cookie,第一次请求时,都会显示编上Session ID的URL。

request.getSession();out.println(response.encodeURL("index.jsp"));

当再次请求时,如果浏览器没有禁用Cookie,则容器可以从Cookie(从cookie标头)中取得Session ID,此时encodeURL()就只会输出index.jsp。如果浏览器禁用Cookie,则encodeURL()就会继续在URL上编上Session ID

HttpServletResponse的另一个方法encodeRedirectURL()方法,可以在要去浏览器重定向时,在URL上编上Session ID。

0 0