JSP Session Attribute Example





Hey guys in this article, you will learn everything you need to know about Sessions in JSP with full code example.

Read More:

Overview


  • JSP session is created once for user’s browser session.
  • It is unique for each user
  • It is commonly  used when you need to keep track of user’s actions

Add data to the session object

session.setAttribute(name, value);

Example:

Set<String> todos = new HashSet<String>();
session.setAttribute("todos", todos);

Retrieve data from session object

Object session.getAttribute(name);

Example:

Set<String> todos = (Set<String>) session.getAttribute("todos");

Complete Example


Follow the below steps to understand the complete example

Create a Project


You can check the following post to create a new Dynamic Web Project

Create a JSP file


Create SessionDemo.jsp file under WebContent and add the following content

<%@page import="java.util.HashSet"%>
<%@page import="java.util.Set"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	
	<form action="SessionDemo.jsp">
		Add New Todo: <input type = "text" name="todo" />
		<input type = "submit" value="Submit" />
	</form>
	
	<%
		
		Set<String> todos = (Set<String>) session.getAttribute("todos");
	
		if(todos == null) {
			todos = new HashSet<String>();
			session.setAttribute("todos", todos);
		}
	
		String todo = request.getParameter("todo");
		if(todo != null) {
			todos.add(todo);
		}
		
	%>
	<br/><br/>
	<b>My upcoming todos:</b>
	<ol>
		<%
			for(String temp : todos) {
				out.println("<li>"+temp+"</li>");
			}
		%>
	</ol>
	
</body>
</html>

Run the file


Right click on the File, choose Run As, choose Run on Server. It will open in a default web browser, you will see the following content
13

That’s it for this post, if you like this post, please share this post with your friends and collogues and also share this on your social media profiles.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply