How do I write and read object from HTTP Session?

In this post you will learn how to write and read object from HTTP Session in JavaServer Page. The first example that we are looking at is using the classic JSP scriptlet, this is a very old way to work with JSP, but it is good for you to know a history. We write a JSP scriptlet inside the <% %> symbols. We can use the provided session object. To set an attribute in the session object we use the setAttribute(String name, Object value) method. In the example we create an attribute called loginDate and set the value to the current date.

To read a value from a session object we use the getAttribute(String name) method. This method return a type of Object, so we need to cast it to the original object. In this case we cast it to a java.util.Date. And then we print out the value read from the session object.

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Write</title>
</head>
<body>
<%
// Creates a session attribute named login-date to store a java.util.Date.
session.setAttribute("loginDate", new Date());

// Read back the java.util.Date object from the session attribute.
Date loginDate = (Date) session.getAttribute("loginDate");
%>
Login Date: <%= loginDate %>
</body>
</html>

The second way that you can use to read values from session object is using the JSP Expression Language (EL). It looks like the following code snippet. You can use the sessionScope implicit object combined with the session attribute name. You can see two ways to use the sessionScope object below. The simplest one is to use the attribute name as the EL expression, and it will look smartly to find the value in the available scope.

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Read EL</title>
</head>
<body>
<p>Login Date: ${sessionScope.loginDate}</p>

<p>Login Date: ${sessionScope["loginDate"]}</p>

<p>Login Date: ${loginDate}</p>
</body>
</html>
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.