What is session management java

What is session management in Java?

Session management is not something limited to Java and servlets. Here’s roughly how it happens:

  1. The HTTP protocol is stateless, so the server and the browser should have a way of storing the identity of the user through multiple requests
  2. The browsers sends the first request to the server
  3. The server checks whether the browser has identified with the session cookie (see below) 3.1. if the server doesn’t ‘know’ the client:
    • the server creates a new unique identifier, and puts it in a Map (roughly), as a key, whose value is the newly created Session. It also sends a cookie response containing the unique identifier.
    • the browser stores the session cookie (with lifetime = the lifetime of the browser instance), containing the unique identifier, and uses it for each subsequent request to identify itself uniquely.

3.2. if the server already knows the client — the server obtains the Session corresponding to the passed unique identifier found in the session cookie

Now onto some the questions you have:

  • the session timeout is the time to live for each session map entry without being accessed. In other words, if a client does not send a request for 30 minutes (from your example), the session map will drop this entry, and even if the client identifies itself with the unique key in the session cookie, no data will be present on the server.
  • different gmails (and whatever site) can be opened in different browsers because the session cookie is per-browser. I.e. each browser identifies itself uniquely by either not sending the unique session id, or by sending one the server has generated for it.
  • logging from different PCs is the same actually — you don’t share a session id
  • logging-out is actually removing the entry for the session id on the server.

Note: the unique session id can alternatively be stored:

  • in a cookie
  • in the URL (http://example.com/page;JSESSIONID=435342342)
  • 2 or 3 other ways that I don’t recall and aren’t of interest

Solution 2

What does it indicate actually ?

The lifetime of a session. The session expires if there is no transaction between the client and the server for 30 minutes (per the code segment)

Is is scope of whole project ?

It has application scope. Defined for each web application

Another point confusing me is how can we separate the session scope of multiple request in the same project? Means if I am logging in from a PC & at the same time I am logging in from another PC, does it differentiate it ?

Yes. The session ids (JSESSIONID for Apache Tomcat) will be different.

Also, another confusing thing is the browser difference. Why does the different Gmails possible to open in different browsers ?

Each login by the same user from a different browser is a different session altogether. And the cookies set in one browser will not affect in another. So different Gmail instances are possible in different browsers.

And Gmail can prevent a session from Login to Logout. How is it maintained with our personal web ?

Источник

Сессии(Session) в Java

Сегодня я расскажу вам про Session в Java, и ознакомлю вас с тем, как работает управление сессиями.

Интервал времени, в течение которого две системы (т.е. клиент и сервер) обмениваются данными друг с другом, можно назвать сеансом. Проще говоря, сеанс – это состояние, состоящее из нескольких запросов и ответов между клиентом и сервером.

Это известный факт, что HTTP и веб-серверы не имеют состояния. Следовательно, единственный способ поддерживать состояние пользователя – использовать технологии, которые реализуют отслеживание сеанса. Отслеживание сеансов в сервлетах может быть реализовано несколькими способами, одним из которых являются файлы cookie. Однако у них есть несколько недостатков:

  • Только текстовая информация может быть сохранена ими.
  • Если файлы cookie отключены пользователем, веб-приложение не сможет их использовать.
  • Один файл cookie может содержать не более 4 КБ данных.
  • Другой способ реализовать отслеживание сеансов – создание сеансов с уникальными идентификаторами сеансов для каждого пользователя в сервлете Java.

Http Session Interface

Сервлеты в Java предоставляют интерфейс, известный как «HttpSessionInterface». Они состоят из различных методов, некоторые из которых обсуждаются ниже:

  • public HttpSession getSession (логическое создание): этот метод получает сеанс, связанный с запросом. Если он недоступен или отсутствует, создается новый сеанс, основанный на указанном логическом аргументе.
  • public String getId(): уникальный метод сеанса возвращается этим методом.
  • public long getCreationTime(): время, когда был создан сеанс, возвращается этим методом. Измеряется в миллисекундах.
  • public long getLastAccessedTime(): время, когда сеанс последний раз был доступен, возвращается этим методом. Измеряется в миллисекундах.
  • public void invalidate(): сессия может быть признана недействительной с помощью этого метода.

Пример: в приведенном ниже примере мы использовали методы getAttribute() и setAttribute() интерфейса HttpSession.

index.html

Переходя ко второму примеру

Servlet1.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet1 extends HttpServlet < public void doGet(HttpServletRequest request, HttpServletResponse response)< try< response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Welcome "+name); pwriter.print("Here is your password: "+password); HttpSession session=request.getSession(); session.setAttribute("usname",name); session.setAttribute("uspass",password); pwriter.print("view details"); pwriter.close(); >catch(Exception exp) < System.out.println(exp); >>

Переходя к третьему примеру

Servlet2.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet2 extends HttpServlet < public void doGet(HttpServletRequest request, HttpServletResponse response)< try< response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); HttpSession session=request.getSession(false); String myName=(String)session.getAttribute("usname"); String myPass=(String)session.getAttribute("uspass"); pwriter.print("Name: "+myName+" Pass: "+myPass); pwriter.close(); >catch(Exception exp) < System.out.println(exp); >> >

web.xml

  MyServlet1 Servlet1  MyServlet1 /loginform  MyServlet2 Servlet2  MyServlet2 /Welcome   

У этого интерфейса есть различные преимущества и недостатки, перечисленные ниже:

  • Все виды объектов, такие как база данных и текст, могут быть сохранены в сеансе.
  • Сессии безопасны.
  • Поскольку объект сеанса хранится на сервере, производительность снижается.
  • Сериализация и десериализация также приводят к накладным расходам.

Весьма выгодно использовать HttpSessionInterface для отслеживания сеанса.

Источник

Session Management in Java Web Apps

Join the DZone community and get the full member experience.

Today, we’re going to walk through how session management works in the context of Java web applications. In order to see how the flow works, we’ll start with this diagram, which we’ll explain in more detail below.

Session Creation Flowchart

  1. The user requests a webpage.
  2. The browser sends the request to the web server.
  3. The server sees that there is no «session related information/identifier» in the request. So it creates a new session (and a new session identifier — the JSESSIONID).
  4. The server sends the JSESSIONID back to the client (e.g. in a cookie, along with the main HTML response).
  5. At this point, both the server and the client have the same session identifier (JSESSIONID) with them.
  6. From here on, when the browser sends additional requests to the server, it has to send the session identifier (JSESSIONID) as part of the request as well. (Note: Whenever a browser sends a request to a web server, all cookies set by the same server are automatically sent in the request. So, the JSESSIONID cookie also gets sent to the server automatically).
  7. When the server gets a request, it checks if the browser sent a session identifier as part of the request. If yes, the server treats the request as part of the same session.
  8. This handshake goes on until the session gets destroyed (or until it expires).

What if Cookies Are Blocked?

At times, users/browsers may not accept cookies from certain servers (for security/privacy reasons). To deal with this case, web servers also support passing the session identifier in the URL (URL rewriting):

  1. When the server creates a session, it «has to» send the session identifier to the client in some way or another (so that the client can then send it back to the server during subsequent requests).
  2. Initially, the server doesn’t know if the client has blocked cookies or not. So it sends the JSESSIONID to the client in two ways:
    1. In a cookie.
    2. As a URL parameter (e.g. http://www.abc.com;jsessionid=123xyz).
    • If the request contains the JSESSIONID cookie, it means that the client does accept cookies. So the server can rely on cookies for session management and continue.
    • If not, the server understands that cookies are blocked and it continues to use the URL parameter approach («URL rewriting»). Note: You have to take some steps to make sure this works correctly — e.g. if your webpage has hyperlinks to other pages, you have to encode them using the response.encodeURL() method

    How Are Sessions Destroyed?

    1. Timeout: If the server doesn’t receive any requests for a given session within a certain period of time, it invalidates the session. This happens when the user either closes the browser or leaves it open without any activity.
    2. Explicit logout pages: Servlets/JSPs can invalidate the session using session.invalidate().

    What Happens When the Browser Is Closed?

    1. Cookie approach: The JSESSIONID cookie is a «session only» cookie, so the browser deletes it as soon as the browser is closed. So if you open another window and visit the same web app, the server would treat the request as a brand new request that is not part of any session.
    2. URL rewriting approach: If you copied the URL with the JSESSIONID, close the browser, open a new browser window and use the copied URL. It will work as long as the session has not timed out. This also poses a security risk (if someone else knows the full URL with the JSESSIONID, they could use it, and if the session was still active, they could do stuff on behalf of someone else). This is one of the reasons why cookies are preferred over URL rewriting.

    Published at DZone with permission of Ashutosh Agrawal . See the original article here.

    Opinions expressed by DZone contributors are their own.

    Источник

    Читайте также:  Сколько всего тегов css
Оцените статью