Using sessions in java

How to use Session in Java web application

In this Java web tutorial, you will understand session management in Java web application development, with useful code examples. Let’s get started with the definition of session.

1. What is Session?

In terms of world wide web, a session indicates a period of time that a single user visits a website. A session starts when the user requests for the first page. And during a session, the user can view as many pages as he wants. The session ends if the user hasn’t requested any pages for a given amount of time (timeout). The session timeout varies, depend on server configuration – typically from 15 to 30 minutes.

Because the HTTP protocol is stateless, the server can track session via cookies, URL rewriting or hidden form fields – to identify a single user across different requests. Session tracking using cookies is the primary mechanism. In case the user’s web browser doesn’t support cookies, then URL rewriting or hidden form fields can be used.

In web development, programmers use session mechanism to manage user’s information that persists only in particular session, such as authentication state, username or any data that need to be shared across requests.

Читайте также:  Перевести html в rtf

2. Session Management in Java

In Java, a HttpSession object represents the session of a particular user. Note that HttpSession is an interface defined in the javax.servlet package, whereas the actual implementation is injected to the HttpServletRequest by the servlet container (i.e. the server like Tomcat).

You can store user-related information in a session in form of key and value pairs. The HttpSession interface defines the setAttribute(key, value) method to store a key-value entry and getAttribute(key) method to get value of a specified key.

By default, Java use cookies for session tracking. A cookie with the name JSESSIONID is stored temporarily in the web browser. It is used to identify the same user across different requests.

3. Getting or Creating a Session

By default, a session is automatically created when the user visits the website. To obtain the HttpSession object representing the user’s session, invoke the getSession() method of the HttpServletRequest interface in doGet() or doPost() method of a Java Servlet. For example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < HttpSession session = request.getSession(); // work with the session. >

Note that the HttpServletRequest . getSession() method returns the current session associated with the request, or create a new one if the request doesn’t have a session. That means the returned HttpSession object is always not null.

To get a session without creating a new one if not exist, you can use invoke getSession(false) on the HttpServletRequest :

HttpSession session = request.getSession(false); if (session != null) < // a session exists >else < // no session >

In this case, the returned value can be null if no session exists – hence the if-else check for nullability is needed. That also means getSession() is equivalent to getSession(true) .

For your reference, the following Java Servlet prints the session ID, creation time and last accessed time of the current session:

package net.codejava; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; @WebServlet("/test_session") public class TestSessionServlet extends HttpServlet < private static final long serialVersionUID = 1L; public TestSessionServlet() < super(); >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < HttpSession session = request.getSession(); PrintWriter writer = response.getWriter(); writer.println("Session ID: " + session.getId()); writer.println("Creation Time: " + new Date(session.getCreationTime())); writer. println("Last Accessed Time: " + new Date(session.getLastAccessedTime())); >>

Test Session Java Servlet

4. Binding Data to a Session

To store a value in a session, use the method setAttribute(key, value) of the HttpSession object. For example, the following statement stores username of the user:

session.setAttribute("username", "Daniel Tran");

Here, the key is username and value is Daniel Tran . Data stored in a session is managed by the server and will be deleted when the session ends.

You can store any kind of object in the session. For example, the following code stores a List of Student objects in the session:

List students = studentDao.getStudents(); session.setAttribute("listStudent", students);

Each user is associated with different HttpSession object, so the values stored for user #1 are different than the values stored for user #2 — although the key is the same.

If the key is already associated with a value, then the old value is replaced by the new one. So you can use the setAttribute() method to update value in the session.

Read value from session in Java Servlet:

To get value from a session, use the getAttribute(key) method of the HttpSession object. For example, the following code gets value of the username attribute from the session:

String username = (String) session.getAttribute("username");

We need a cast to String type because the getAttribute() method always returns a value of Object type.

The following statement reads a List collection from the session:

List listStudents = (List) session.getAttribute("listStudent");

Note that the getAttribute(key) method will return null value if the given key is not found in the session.

Read value from session in JSP:

In JSP, to read and display value of an attribute stored in the session, just use EL (expression language) as follows:

Here, the JSP processor will find an attribute username in possible scopes, including the session. Or you can specify the session scope explicitly in the expression:

Remove value from session:

To delete a value associated with a key from the session, use the removeAttribute(key) method. For example:

session.removeAttribute("username");

5. Configure Session Timeout

If a user has been idle (has not made any requests) for a given amount of time, his session expires – which means all the data bound to his session is removed from the server – the session is destroyed. Each server has different default value for global session timeout, e.g. 30 minutes in Apache Tomcat.

You can set session timeout for an individual web application by modifying its web deployment descriptor file ( web.xml ). For example:

You can set timeout value for an individual session programmatically like this:

session.setMaxInactiveInterval(300);

Read this article for more details about setting session timeout in Java.

6. Invalidate a Session

By default, a session is destroyed only after the user has been idle for a timeout period. In case you want to destroy an individual session immediately, call the invalidate() method like this:

API Reference:

Other Java Servlet Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Сессии(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 для отслеживания сеанса.

Источник

Оцените статью