JSP Sessions Example

Sessions are started automatically in JSP pages.
You can access current session by prebuilt session object.

Create sessions.jsp file on your Tomcat's webapps/ROOT directory :


<%@page import="java.util.Date"%>
<%
out.print("Session Creation Time:" + new Date(session.getCreationTime()));
out.print("<BR>");
out.print("Last accessed Time:" + new Date(session.getLastAccessedTime()));
out.print("<BR>");
out.print("Session ID:"+session.getId());
%>


and launch it (for example http://localhost:8080/sessions.jsp)

it prints:

Session Creation Time:Sat Jun 14 19:28:06 EEST 2008
Last accessed Time:Sat Jun 14 19:33:34 EEST 2008
Session ID:365A3F239D1E54FD43EA0F7CBA1931EF

Now we are able to access the session. We can store objects in session objects.
This can help share objects between JSP pages.

Sessions are widely used for authentication purposes.

For example , let this be index.jsp as default page :


<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if ("admin".equals(userName) && "adminpass".equals(password) ) { //Session start
session.setAttribute("userName",userName);
session.setAttribute("role","admin");
response.sendRedirect("/main.jsp");
}
else out.print("Logon failed");
%>
<form action="index.jsp" method="post">
Enter Username: <input name="userName"> <br>
Enter Password: <input name="password"> <br>
<input type="submit">
</form>


The sample code above get username and password from user. If username and password are ok , username and role objects are stored in session and redirects to main.jsp otherwise sends an http error.

And in main.jsp we authenticate user based on username and role :


<%
String userName = session.getAttribute("userName");
String role = session.getAttribute("role");
if ( userName == null || ! "admin".equals(role) ) {
response.sendError(403,"You are not authorized to view this page");
return;
}
%>

This authentication part can be a seperate jsp and included in every page that needs authentication. Ideally , username , password and role lookup should be from database or from a directory service like LDAP or Active Directory.

Technorati Profile

Comments

Popular posts from this blog

Connect via SSH without a password from MacOS to Linux with an SSHKEY

Read and Write Files in Java

Install Mac OS on windows laptop