Home > Java and Web > Session Tracking [ Part 2 ]

Session Tracking [ Part 2 ]

HttpSession

HttpSession merupakan interface yang  menyediakan cara untuk melakukan tracking terhadap user. Web Container menggunakan interface ini untuk membuat session antara HTTP client dan HTTP server. Untuk memperoleh session object dapat menggunakan method getSession() dari interface HttpServletRequest.
HttpSession session = request.getSession();

Berikut ini method dari interface HttpSession yang sering digunakan :

  • public Object getAttribute(String name)
  • public Enumeration getAttributeNames()
  • public long getCreationTime()
  • public String getId()
  • public long getLastAccessedTime()
  • public int getMaxInactiveInterval()
  • public void invalidate()
  • public void removeAttribute(String name)
  • public void setAttribute(String name, Object value)
  • public void setMaxInactiveInterval(int interval)

Untuk lebih detail tentang HttpSession dapat dilihat disini .

Berikut ini contoh penggunaan HttpSession

File : Login.jsp

<%@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>
        <form method="post" action="Login">
               <table>
                     <tr>
                         <td>User Name</td>
                         <td><input type="text" name="username"></td>
                     </tr>
                     <tr>
                         <td>Password</td>
                         <td><input type="password" name="password"> </td>
                     </tr>
                     <tr><td><input type="submit" value="Login"></td></tr>
               </table>
         </form>
    </body>
</html>

File : Login.java ( Servlet )

package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String username="";
       String password="";
       
       username = request.getParameter("username");
       password = request.getParameter("password");
       
       HttpSession loginSession = request.getSession();
       Date createDateSession = new Date(loginSession.getCreationTime());
       Date lastAccess = new Date(loginSession.getLastAccessedTime());
       loginSession.setAttribute("username", username);
       loginSession.setAttribute("password", password);
       loginSession.setAttribute("createDate", createDateSession);
       loginSession.setAttribute("lastAccess", lastAccess);
       
       RequestDispatcher rd = request.getRequestDispatcher("/Home.jsp");
       
       rd.forward(request, response);
       
    }

}

File : Home.jsp

<%@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>
        <% if( session.getAttribute("username") != null && session.getAttribute("password") != null ){ %>
        <h5>Welcome, <%out.println(session.getAttribute("username")); %> </h5>
        <h5>Session ID: <%out.println(session.getId()); %> </h5>
        <h5>Session was created on: <%out.println(session.getAttribute("createDate")); %> </h5>
        <h5>Last access: <%out.println(session.getAttribute("lastAccess")); %> </h5>
        <form action="Logout">
             <table>
                 <tr><td><input type="submit" value="Log Out"></td></tr>
             </table>
        </form>
        <%} else {
          out.println("<b>You have not login yet </b>");
          RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
          rd.include(request, response);
        }%>
    </body>
</html>

File : Logout.java ( Servlet )

package Action;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Logout extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       System.out.println("doGet");
       HttpSession loginSession = request.getSession();
       loginSession.invalidate();
       RequestDispatcher rd = request.getRequestDispatcher("/Login.jsp");
       rd.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("doPost It");
       
    }
 
}

File : web.xml

....

 <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>Action.Login</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>Action.Logout</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>

<session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>

....

Halaman Login:

Login

Login

Halaman Home:

Home

Home

Semoga bermanfaat.

Referensi : Dari berbagai sumber.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: