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>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024