Thursday, 1 December 2016

How to manage session from login to logout in Java.

An application may begin with some kind of user identification and validation that must be propagated through several other Web pages. Several approaches can be taken to accommodate this need, depending on the requirements of the application. Because the Web server doesn’t remember clients from one request to the next, the only way to maintain a session is for clients to keep track of it.
Without going into details about session concept (you can get it from web), I focus on programming techniques to manage session in web applications.
How to create session?
HttpSession session = req.getSession(true);
Above code will create session on server.
To use class HttpSession, you will have to import package by using code
import javax.servlet.http.*;
How to set session value?
After creation of session, we required to set session value using following code
session.setAttribute("session name", “session value”);
How to print session value?
out.println((String)session.getAttribute("session name"));
How to remove session?
session.removeAttribute("session name");
How to allow to access page content if session is created (means authenticated user is logged in and session is created) and denied if session is not created?
Login example 1 click here
Login example 2 click here

It is a basic requirement of validating authenticated user on every page if he/she has logged in till his/her logged out. You can use following code.
if(session.getAttribute("session name")!=null)
{
// page content if user is valid
}
else
{
out.println("you are not logged in");
}
How to destroy session?
If user want to be logged out from his/her session, you can provide logged out facility to destroy session using code
session.invalidate();



No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...