CalculatorServlet

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.

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) .

Читайте также:  Html транскрипция на русском

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.

Читайте также:  Wiki inpas ru index php

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.

Источник

Работа сервлета с сессиями

Если несколько запросов идут от одного клиента, то говорят, что между клиентом и сервером установилась сессия. Для контроля этого процесса у контейнера есть специальный объект HttpSession.

Когда клиент обращается к сервлету, то контейнер сервлетов проверяет, есть ли в запросе параметр ID сессии. Если такой параметр отсутствует (например, клиент первый раз обращается к серверу), тогда контейнер сервлетов создает новый объект HttpSession, а также присваивает ему уникальный ID.

Объект сессии сохраняется на сервере, а ID отправляется в ответе клиенту и по умолчанию сохраняется на клиенте в куках. Затем, когда приходит новый запрос от того же клиента, то контейнер сервлетов достает из него ID, и по этому ID находит правильный объект HttpSession на сервере.

Читайте также:  Html img link to page

Получить объект сессии можно из запроса (объект HttpServletRequest), у которого нужно вызвать метод getSession(). Он возвращает объект HttpSession.

Зачем нужна сессия? В ней можно хранить информацию о клиенте между вызовами. У нее внутри есть что-то вроде HashMap, в котором можно хранить объекты по ключам. И несколько методов для этого:

Методы Описание
1 setAttribute(String name, Object o) Добавляет объект внутрь сессии
2 getAttribute(String name) Получает объект из сессии
3 removeAttribute(String name) Удаляет объект из сессии

Давай напишем сервлет, который будет суммировать все передаваемые ему числа из разных запросов:

 public class CalculatorServlet extends HttpServlet < @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException < // Получаем атрибут “sum” из сессии HttpSession session = request.getSession(); Integer sum = (Integer) session.getAttribute("sum"); //Обрабатываем ситуацию, когда такого атрибута у сессии еще нет if (sum == null) sum = 0; // Получаем параметр “n” из запроса String n = request.getParameter("n"); sum += Integer.parseInt(n); // Записываем атрибут “sum” в сессию session.setAttribute("sum", sum); // Печатаем HTML в качестве ответа для браузера PrintWriter out = response.getWriter(); out.println(""); out.println("   "); out.println(""); out.println(" 

Sum == " + sum + "

"); out.println(""); out.println(""); > >

4.2 Подробнее об HttpSession

Что еще важного мы не сказали об объекте HttpSession?

Во-первых, это имя J SESSION ID. Именно под ним в куках хранится ID сессии. Как видите, запомнить его довольно легко: J+SESSION+ID .

Во-вторых, у сессии есть еще несколько полезных методов:

Методы Описание
1 getAttributeNames() Возвращает список всех ключей, которые храниться в сессии
2 getId() Возвращает ID-сессии (строка)
3 isNew() Возвращает true, если объект сессии был создан в текущем запросе
4 setMaxInactiveInterval(int seconds) Устанавливает интервал неактивности сессии в секундах
5 invalidate() Удаляет из сессии все объекты

Тут все методы очевидны, а про setMaxInactiveInterval() мы поговорим немного подробнее.

Если сервер будет хранить десятки тысяч сессий, включая данные клиентов, которые заходили к нему в прошлом месяце, то у него банально закончиться память. Поэтому есть способ установить “время жизни сессии”.

Если в течение interval времени сессией никто не пользовался, то она самоочищается — из нее удаляются все объекты, которые она хранила. Это сделано для экономии памяти.

По умолчанию этот интервал равен 1800 секундам == 30 минутам. Если установить значение -1, то сессия будет “вечной” и удалится только когда пользователь закроет вкладку браузера (ну или клиент разорвет соединение).

 // получение всех ключей Enumeration keys = session.getAttributeNames(); while( keys.hasMoreElements() )
 // установка интервала неактивности session.setMaxInactiveInterval(60*60*24); // 1 день session.setMaxInactiveInterval(-1); // до закрытия браузера 
 // удаление всех данных из сессии session.invalidate(); 

Источник

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