How to handle Sessions in JSP

In the previous article, we have seen How to handle cookies on the JSP page. In this article, we will discuss How to handle sessions in Jsp, the best way to keep track of sessions on the JSP page, and login and logout example in JSP.

In JSP session is a way to store information to be used across multiple pages until the user session is active. We will cover session Tracking its method, and an example showing session Tracking.

Session in JSP

JSP provides the HttpSession Interface which provides a way to identify a user across more than one page. Session means a particular interval of time. Session Tracking is used to keep the state of the user across pages. The following are the methods we used for session tracking.

Cookies

One way we have seen earlier is Cookies. A web server assigns a uniques session Id to each request. But the cookie is not recommended by many because many browsers don’t support cookies.

Hidden Form Field

Another way is Hidden Form Fields In this a web server can send a hidden HTML form filed with session Id. But this is not a good way because <a href > tag does not result in form submission.so this method does not support session Tracking.

<input type = "hidden" name = "session_id" value = "abc">

URL Rewriting

One more way is URL Rewriting. In this method, extra data is appended at the end of the URL that identifies the session. It is a better method as compared to both Cookies and Hidden form fields. The drawback here is we have to generate a URL dynamically to assign a session ID.

http://codedec.com/first.html;sessionid=abc

Http session Object

In this method, JSP uses the HttpSession Interface provided by the servlet. In this, the Servlet container creates a separate session-id for the users which helps in identifying a user in the system. (like we have a unique id for different employees).We get the object by calling method getSession() of HttpServletRequest.

HttpSession session=request.getSession();

Methods of HttpSession Interface

  • public String getId(): This method returns the id value.
  • public long getCreationtime(): This method returns the time at which the session is created.
  • public long getLastAccessedTime(): This method returns the last time at which the user sends a request associated with the session id.
  • public void invalidate(): This method invalidates the object.
  • public Object getAttribute(String name): This method returns the object bound to the specified name in the session.
  • public Enumeration getAttributeNames(): This method returns all the objects associated with the session.
  • public int getMaxInactiveInterval(): This method returns the maximum time session will remain between client and server.
  • public boolean isNew(): This method returns true if the client does not know about the session.
  • public void removeAttribute(String name): This method returns the object bound to the specified name.
  • public void setAttribute(): This method sets the object to the session.
  • public void setMaxInactiveInterval(int interval): This method sets the time in which between the client request before the web container invalidates the session.

How to track sessions in JSP?

In this example, we simply create a login page and create the Session for the request.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link href="css/style.css" type="text/css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
  integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
  crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
  integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ"
  crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script
  src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
  integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
  crossorigin="anonymous"></script>
</head>
<body>
  <div class="container-fluid bg">
    <div class="row ">
      <div class="col-md-4 col-sm-4 col-xs-12"></div>
      <div class="col-md-4 col-sm-4 col-xs-12">

        <form action="login.jsp">
          <div class="form-group">
            <label for="exampleInputEmail1">Email</label> <input type="email"
              class="form-control" id="exampleInputEmail1" placeholder="Email"
              name="uname">
          </div>
          <div class="form-group">
            <label for="exampleInputPassword1">Password</label> <input
              type="password" class="form-control" id="exampleInputPassword1"
              placeholder="Password" name="pass">
          </div>
          <button type="submit" class="btn btn-default">Log In</button>
        </form>
      </div>
      <div class="col-md-4 col-sm-4 col-xs-12"></div>
    </div>
  </div>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <%
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
if(uname.equals("admin@yahoo.com") && pass.equals("admin123"))
{
  session.setAttribute("name",uname);
  session.setAttribute("pass", pass);
  response.sendRedirect("welcome.jsp");
  
}
%>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/style.css" type="text/css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
  integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
  crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
  integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ"
  crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script
  src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
  integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
  crossorigin="anonymous"></script>
<title>Insert title here</title>
</head>
<body>
  <%
out.print("<h1>Username "+session.getAttribute("name")+"<br></h1>");
out.print("<h1>Password "+session.getAttribute("pass")+"<br></h1>");

%>
</body>
</html>

style.css

@CHARSET "ISO-8859-1";
.bg{
  background: url('../image/img1.jpg') no-repeat;
  width: 100%;
  height: 100%;}

output

Thus we have seen the How to track sessions in JSP.

In the next article of this tutorial, we will create the registration and Login Page in JSP.