In this tutorial you will learn about the JSP Session and its application with practical example.
JSP Session
This is the instance of javax.servlet.http.HttpSession which provides a way to identify a user across more than one page request. It behaves like same as session in servlet. The session is used for Add, Remove attributes and also we can get session information of logged in user.
#Setting Attributes in Session: With the help of setAttribute(String name, Object value) Method we can set our data in session.
1 |
session.setAttribute("user", name); |
#Getting Attributes from Session: With the help of getAttribute(String name) Method we can get our data from session. It returns the object bound with the specified name in the session.
1 |
String name=(String)session.getAttribute("user"); |
Example:Let’s get understand it by an example. Create index.jsp file in your project like below
#index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <pre> <form action="session.jsp"> Name : <input type="text" name="uname"> Email : <input type="text" name="email"> <input type="submit" value="Click"><br/> </pre> </form> </body> </html> |
#Output: The output of this index.jsp file will look like below image.
#session.jsp: From here we will set attributes in our session, check below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String name = request.getParameter("uname"); String email=request.getParameter("email"); out.print("Welcome " + name+ " Email :"+email); session.setAttribute("user", name); //set attribute in session session.setAttribute("email", email); %> <a href = "session_second.jsp">Next Page</a> </body> </html> |
#Output: When you will click on index.jsp’s “click” button so this code will run and the output of this above code will look like below image and also we have set attributes in session from above code.
#session_second.jsp: When you will click on “Next Page” of “session.jsp” page, The below code will run. Here we will get session attributes which you have set from “session.jsp” page.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <body> <% String name=(String)session.getAttribute("user"); //Getting Session Attribute String email=(String)session.getAttribute("email"); out.print("Welcome to Session Page: Name"+name+ " Email"+email); %> </body> </html> |
#Output: The output of this code will look like below image.