[Servlet&JSP] HttpSession会话管理

我们能够将会话期间必须共享的资料保存在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);
    }
}

在登录时,假设username和password正确,就会取得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来进行会话管理时,设置为属性的数据是保存在server端的,而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。

原文地址:https://www.cnblogs.com/gavanwanggw/p/7055889.html