本文共 23188 字,大约阅读时间需要 77 分钟。
Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through different ways, such as Cookies, HttpSession API, URL rewriting etc.
Java Servlet Web应用程序中的会话管理是一个非常有趣的主题。 Java Servlet中的会话通过不同的方式进行管理,例如Cookies, HttpSession API,URL重写等。
This is the third article in the series of Web Applications tutorial in Java, you might want to check out earlier two articles too.
这是Java Web应用程序系列教程中的第三篇文章,您可能也想看看前面的两篇文章。
This article is aimed to explain about session management in servlets using different techniques and with example programs.
本文旨在说明有关使用不同技术和示例程序的Servlet中的会话管理。
HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously.
But sometimes in web applications, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client.
Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
There are several ways through which we can provide unique identifier in request and response.
That’s why we need Session Management API and J2EE Servlet technology comes with session management API that we can use.
HTTP协议和Web服务器是无状态的,这意味着对于Web服务器,每个请求都是要处理的新请求,它们无法识别它是否来自先前一直在发送请求的客户端。
但是有时在Web应用程序中,我们应该知道客户端是谁,并相应地处理请求。 例如,购物车应用程序应该知道谁在发送添加商品的请求以及必须在哪个购物车中添加商品,或者谁在发送结帐请求,以便可以向正确的客户收取费用。
会话是客户端和服务器之间的转换状态,它可以包含客户端和服务器之间的多个请求和响应。 由于HTTP和Web Server都是无状态的,因此维护会话的唯一方法是在每次请求和响应中在服务器和客户端之间传递有关会话的某些唯一信息(会话ID)时。
我们可以通过几种方式在请求和响应中提供唯一的标识符。
这就是为什么我们需要会话管理API以及我们可以使用的会话管理API附带的J2EE Servlet技术的原因。
Cookies are used a lot in web applications to personalize response based on your choice or to keep track of session. Before moving forward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a small web application.
We will create a dynamic web application ServletCookieExample with project structure like below image.
Deployment descriptor web.xml of the web application is:
Welcome page of our application is login.html where we will get authentication details from user.
Login Page
Here is the LoginServlet that takes care of the login request.
Notice the cookie that we are setting to the response and then forwarding it to LoginSuccess.jsp, this cookie will be used there to track the session. Also notice that cookie timeout is set to 30 minutes. Ideally there should be a complex logic to set the cookie value for session tracking so that it won’t collide with any other request.
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%String userName = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue();}}if(userName == null) response.sendRedirect("login.html");%>Hi <%=userName %>, Login successful.
Notice that if we try to access the JSP directly, it will forward us to the login page. When we will click on Logout button, we should make sure that cookie is removed from client browser.
There is no method to remove the cookie but we can set the maximum age to 0 so that it will be deleted from client browser immediately.
When we run above application, we get response like below images.
在Web应用程序中,Cookie经常用于根据您的选择个性化响应或跟踪会话。 在继续使用Servlet会话管理API之前,我想展示如何通过小型Web应用程序跟踪cookie的会话。
我们将创建一个动态Web应用程序ServletCookieExample ,其项目结构如下图所示。
Web应用程序的部署描述符web.xml为:
我们应用程序的欢迎页面是login.html,我们将从用户那里获取身份验证详细信息。
Login Page
这是处理登录请求的LoginServlet。
注意我们为响应设置的cookie,然后将其转发到LoginSuccess.jsp,该cookie将在此处用于跟踪会话。 还要注意,cookie超时设置为30分钟。 理想情况下,应该有一个复杂的逻辑来设置cookie值以进行会话跟踪,以使其不会与任何其他请求冲突。
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%String userName = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue();}}if(userName == null) response.sendRedirect("login.html");%>Hi <%=userName %>, Login successful.
注意,如果我们尝试直接访问JSP,它将把我们转发到登录页面。 当我们单击注销按钮时,我们应确保从客户端浏览器中删除了cookie。
没有删除Cookie的方法,但是我们可以将最长期限设置为0,以便将其立即从客户端浏览器中删除。
当我们在上面的应用程序上运行时,我们得到如下图所示的响应。
Servlet API provides Session management through HttpSession
interface. We can get session from HttpServletRequest object using following methods. HttpSession allows us to set objects as attributes that can be retrieved in future requests.
Some of the important methods of HttpSession are:
getAttributeNames()
, removeAttribute(String name)
and setAttribute(String name, Object value)
.getLastAccessedTime()
method.getMaxInactiveInterval()
method.When we use HttpServletRequest getSession() method and it creates a new request, it creates the new HttpSession object and also add a Cookie to the response object with name JSESSIONID and value as session id. This cookie is used to identify the HttpSession object in further requests from client. If the cookies are disabled at client side and we are using URL rewriting then this method uses the jsessionid value from the request URL to find the corresponding session. JSESSIONID cookie is used for session tracking, so we should not use it for our application purposes to avoid any session related issues.
Let’s see example of session management using HttpSession object. We will create a dynamic web project in Eclipse with servlet context as ServletHttpSessionExample. The project structure will look like below image.
login.html is same like earlier example and defined as welcome page for the application in web.xml
LoginServlet servlet will create the session and set attributes that we can use in other resources or in future requests.
Our LoginSuccess.jsp code is given below.
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%//allow access only if session existsString user = null;if(session.getAttribute("user") == null){ response.sendRedirect("login.html");}else user = (String) session.getAttribute("user");String userName = null;String sessionID = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue(); if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();}}%>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %>
User=<%=user %>Checkout Page
When a JSP resource is used, container automatically creates a session for it, so we can’t check if session is null to make sure if user has come through login page, so we are using session attribute to validate request.
CheckoutPage.jsp is another page and it’s code is given below.
Our LogoutServlet code is given below.
package com.journaldev.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LogoutServlet */@WebServlet("/LogoutServlet")public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); break; } } } //invalidate the session if exists HttpSession session = request.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != null){ session.invalidate(); } response.sendRedirect("login.html"); }}
Notice that I am printing JSESSIONID cookie value in logs, you can check server log where it will be printing the same value as Session Id in LoginSuccess.jsp
Below images shows the execution of our web application.
Servlet API通过HttpSession
接口提供会话管理。 我们可以使用以下方法从HttpServletRequest对象获取会话。 HttpSession允许我们将对象设置为可以在将来的请求中检索的属性。
HttpSession的一些重要方法是:
getAttributeNames()
, removeAttribute(String name)
和setAttribute(String name, Object value)
。 getLastAccessedTime()
方法获取上次访问时间。 getMaxInactiveInterval()
方法获取会话超时值。 当我们使用HttpServletRequest getSession()方法创建一个新请求时,它会创建一个新的HttpSession对象,并向响应对象添加一个名称为JSESSIONID且值为会话ID的Cookie。 此cookie用于在客户端的其他请求中标识HttpSession对象。 如果在客户端禁用了cookie,并且我们正在使用URL重写,则此方法将使用请求URL中的jsessionid值来查找相应的会话。 JSESSIONID cookie用于会话跟踪,因此我们不应将其用于应用程序目的,以避免任何与会话相关的问题。
让我们看看使用HttpSession对象进行会话管理的示例。 我们将在Eclipse中创建一个带有ServletHttpSessionExample的servlet上下文的动态Web项目。 项目结构如下图所示。
login.html与前面的示例相同,并在web.xml中定义为应用程序的欢迎页面
LoginServlet servlet将创建会话并设置可在其他资源或将来的请求中使用的属性。
下面是我们的LoginSuccess.jsp代码。
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%//allow access only if session existsString user = null;if(session.getAttribute("user") == null){ response.sendRedirect("login.html");}else user = (String) session.getAttribute("user");String userName = null;String sessionID = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue(); if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();}}%>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %>
User=<%=user %>Checkout Page
使用JSP资源时,容器会自动为其创建一个会话,因此我们无法检查session是否为null来确保用户是否已通过登录页面,因此我们使用session属性来验证请求。
CheckoutPage.jsp是另一个页面,其代码如下。
下面是我们的LogoutServlet代码。
package com.journaldev.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LogoutServlet */@WebServlet("/LogoutServlet")public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); break; } } } //invalidate the session if exists HttpSession session = request.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != null){ session.invalidate(); } response.sendRedirect("login.html"); }}
注意,我正在日志中打印JSESSIONID cookie值,您可以在服务器日志中检查它将与LoginSuccess.jsp中的会话ID值打印相同的值。
下图显示了我们的Web应用程序的执行。
As we saw in last section that we can manage a session with HttpSession but if we disable the cookies in browser, it won’t work because server will not receive the JSESSIONID cookie from client. Servlet API provides support for URL rewriting that we can use to manage session in this case.
The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.
We can encode URL with HttpServletResponse encodeURL()
method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL()
method.
We will create a similar project like above except that we will use URL rewriting methods to make sure session management works fine even if cookies are disabled in browser.
ServletSessionURLRewriting project structure in eclipse looks like below image.
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%//allow access only if session existsString user = null;if(session.getAttribute("user") == null){ response.sendRedirect("login.html");}else user = (String) session.getAttribute("user");String userName = null;String sessionID = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue(); if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();}}else{ sessionID = session.getId();}%>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %>
User=<%=user %> ">Checkout Page
package com.journaldev.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LogoutServlet */@WebServlet("/LogoutServlet")public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); } cookie.setMaxAge(0); response.addCookie(cookie); } } //invalidate the session if exists HttpSession session = request.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != null){ session.invalidate(); } //no encoding because we have invalidated the session response.sendRedirect("login.html"); }}
When we run this project keeping cookies disabled in the browser, below images shows the response pages, notice the jsessionid in URL of browser address bar. Also notice that on LoginSuccess page, user name is null because browser is not sending the cookie send in the last response.
If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.
如上一节所述,我们可以使用HttpSession管理会话,但是如果禁用浏览器中的cookie,它将无法正常工作,因为服务器不会从客户端接收JSESSIONID cookie。 Servlet API提供了对URL重写的支持,在这种情况下,我们可以使用它来管理会话。
从编码的角度来看,最好的部分是,它非常易于使用,并且涉及一个步骤-编码URL。 Servlet URL编码的另一个好处是,它是一种后备方法,只有在禁用浏览器cookie的情况下,它才能启动。
我们可以使用HttpServletResponse encodeURL()
方法对URL进行编码,如果必须将请求重定向到另一个资源,并且想要提供会话信息,则可以使用encodeRedirectURL()
方法。
我们将创建与上述类似的项目,除了使用URL重写方法以确保即使在浏览器中禁用Cookie时,会话管理也能正常工作。
Eclipse中的ServletSessionURLRewriting项目结构如下图所示。
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%>Login Success Page <%//allow access only if session existsString user = null;if(session.getAttribute("user") == null){ response.sendRedirect("login.html");}else user = (String) session.getAttribute("user");String userName = null;String sessionID = null;Cookie[] cookies = request.getCookies();if(cookies !=null){for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue(); if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();}}else{ sessionID = session.getId();}%>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %>
User=<%=user %> ">Checkout Page
package com.journaldev.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LogoutServlet */@WebServlet("/LogoutServlet")public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); } cookie.setMaxAge(0); response.addCookie(cookie); } } //invalidate the session if exists HttpSession session = request.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != null){ session.invalidate(); } //no encoding because we have invalidated the session response.sendRedirect("login.html"); }}
当我们运行此项目时,在浏览器中禁用cookie时,下图显示了响应页面,请注意浏览器地址栏URL中的jsessionid。 还要注意,在LoginSuccess页面上,用户名为null,因为浏览器未发送上次响应中发送的cookie。
如果未禁用Cookie,则URL中不会显示jsessionid,因为Servlet会话API在这种情况下将使用Cookie。
Thats all for session management in java servlets, we will look into Servlet Filters and Listeners and Cookies in future articles.
以上就是Java Servlet中会话管理的全部内容,我们将在以后的文章中介绍Servlet过滤器,侦听器和Cookies。
Update: Check out next article in the series .
更新:查看系列中的下一篇文章。
翻译自:
转载地址:http://ccqzd.baihongyu.com/