Session Handling in JSP
How is Session Handled in JSP?
Explanation
Session Handling becomes mandatory when a requested data need to be sustained for further use. Since http protocol considers every request as a new one, session handling becomes important.
Following are some of the methods to handle session.
- In JSP whenever a request arises the server generates a unique Session ID which is stored in the client machine.
- Cookies store the information in the client browser
- URL rewriting the session information is appended to the end of the URL
- Hidden form fields the sessionID is embedded to GET and POST command.
Example 1 :
<html>
<body>
<form method = "post" action="session2.jsp">
<font>Username<input type = "text" name = "name"></font>gt;
</font><br><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
Example 2 :
<%
String name = request.getParameter("name");
if((name!=null))
{
session.setAttribute("username",name);
}
%>
<a href="session3.jsp">Continue</a>
Example 3 :
<html>
<head>
<title>Welcome to session continued Page</title>
</head>
<body>
<font>Welcome</font> <%= session.getAttribute("username") %>
</body>
</html>
In the first example "session1.jsp" we get the username using a form. When the form is submitted it goes to the second file session2.jsp which is called using form "action" attribute. A session attribute is set here using "session.setAttribute". In the third file "session3.jsp" the same username is displayed using "session.getAttribute".