Pages

Monday, 22 July 2013

Invalidate sessions in struts1.x when pressed back button on IE and will display Session has been Expied please login again

HI,


          I have  made a Login and LogOut page with sessions .Now i have  invalidate the session after  clicking LogOut button.Means that after  logout action no one can access previous pages by clicking back button of browser without  login again.


----------------Lets Start the coding.--------------




Ofter Login to the Application  let us Assume Application Frame contains   below  menus.( In  "LoginSuccess.jsp" page).


ChangePwd                 Project List                     BatchList        LogOut.


in  "LoginSuccess.jsp"  page   Logout menu hiyper link will be like :

<li><a href="logout.do"><font color="green"><b><i>Logout</i></b></font></a></li>



 When i click the Logout button  Action("Logout.do"   will be match at the struts Configuration File)..


"Struts-Config.xml"   code for path matching  :



<action path="/logout" type="com.client.action.LogoutAction" validate="false">
      <set-property property="cancellable" value="true" />
      <forward name="success" path="/Login.jsp" />
    </action>



Action Class of  LogoutAction (com.client.action.LogoutAction)  :

If Session Expired then  Response  will Redirect to "Login.jsp" page. Which means when user click the logout button  it will display  "Login.jsp"  page.


package com.client.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class LogoutAction extends Action
{
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
                    {
               
        HttpSession session = request.getSession(false);
        if (session != null) session.invalidate();
        return mapping.findForward("success");             // it is mapping to success page. so  "Login.jsp" will be open.
       

        }
}





"Login.jsp" page to Login into the Application  with Autharized username and password.

"Login.jsp" Page:


<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

<html:html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
       <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
       <meta http-equiv="expires" content="0">   
   
    <link href="style.css" rel="stylesheet" type="text/css">
    <script language="javascript" src="general.js"></script>
    <script language="javascript">
   
</script>
</head>

    <body bgcolor="#CDB599" text="#000000">

    <html:errors/>
    <html:form action="/login1">
   
   
            <html:text property="userName"  styleId="userName" size="10"/>
            <html:password property="userPassword" size="10"/>
                       <font style="font-size:11px" color="#000000" face="Arial">User Name :</font>
                

        <font style="font-size:11px" color="#000000" face="Arial">Password :</font>
   
        <html:submit value="Log In" />
           
        </font>
   
        </html:form>
    </body>
</html:html>




When Click the Login(button)  it will checks  path(login1) at the Struts-config.xml

"Struts-config.xml"  code   :



<action
      attribute="loginForm1" validate="true"
      input="/Login.jsp"
      name="loginForm1Form"
      path="/login1"
      scope="request"
      type="com.client.action.LoginAction1">
      <set-property property="cancellable" value="true" />
      <forward
        name="success"
        path="/Loginsuccess.jsp"
        redirect="true" />
     <forward name="failure" path="/Login.jsp"></forward>
    </action>




Action Class of  LoginAction1 class (com.client.action.LoginAction1)   :


package com.client.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.client.form.UserDataForm;
import com.client.database.*;
import com.client.form.LoginForm1Form;

import com.client.database.*;

public class LoginAction1 extends Action
{
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception

        {
        LoginForm1Form loginForm1 = (LoginForm1Form) form;
        ActionForward af=null;
        String s;
       
       
         String uname=loginForm1.getUserName();
         String password=loginForm1.getUserPassword();

         System.out.println("uname value is"+uname);
         System.out.println("password value is "+password);

       
            
          if(uname.equals("Client")&&password.equals("Client"))
          {
        // Access Httpsessions for user Expiration time
           
              HttpSession hsession=request.getSession(true);

            UserDataForm userData = new UserDataForm();                   //Setting the values into the bean . These values are  used to Session Expiration in Feture.

           
            userData.setUsername(uname);         //setting username into the bean
            userData.setPassword(password);    //setting password into the bean
          
             hsession.setAttribute("UserData",userData);   //setting bean(UserDataForm) into the session
           
             af=mapping.findForward("success");
       
      }
         else
         {
              s="invalid.wrong";                      // It used  For validation And getting  the "invalid.wrong" value from property file.
             
                      ActionErrors errors = new ActionErrors();
                ActionError error= new ActionError(s);
                errors.add("error",error);
                saveErrors(request, errors);
           
       af=mapping.findForward("failure");
         }
       
   return af;
    }
}




UserDataForm Bean    :



package com.client.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;


public class UserDataForm extends ActionForm
{
   
             private String username;
    private String password;
    private String lastmsg;
   
    public String getUsername()
                 {
        return username;
      }

   
    public void setUsername(String username)
              {
        this.username = username;
    }

   
    public String getPassword()
              {
        return password;
    }

   
    public void setPassword(String password) {
        this.password = password;
    }

        public String getLastmsg()
               {
                 return lastmsg;
    }

   public void setLastmsg(String lastmsg)
             {
       this.lastmsg = lastmsg;
    }
}



Ofter logout from the Application when user clicks the Back button of the browser and trying to perform any Function (like trying to update the password)  then it is showing
message as  Session Has been Expired please  login again.

        For this purpose we need to write the below code in  "chagepwd.jsp"  page.


"Changepwd.jsp" page       :
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>


//It is code for Session Invalidation.


<%@page import="com.client.form.UserDataForm"%>


   <%
    UserDataForm userData = (UserDataForm)request.getSession(false).getAttribute("UserData");
    if (userData == null) {
        userData = new UserDataForm();

        //userData.setLastmsg("Session Expired! Please login again");

        response.sendRedirect("sessionexpired.jsp");
       
        String s2=userData.getLastmsg();
        %>
 <%=s2%>
 <%
   }
%>


<html>
<head>
<title>JSP for ChangePwd form</title>
    </head>
    <body>
    <br/>
    <br/>
   


// This code for updating the password.
 
            <center>
   
       <img src="images/chp3.jpeg"/>
             <br/>
             <html:errors/>
     <html:form action="/changePwd">
       <table border="1">
      
        <tr> <td> <bean:message key="user.oldpwd"/>  </td>
       <td> <html:password property="oldpwd"/>  </td>
       </tr>
        
    <tr> <td><bean:message key="user.newpwd"/></td>
    <td><html:password property="newpwd"/> </td></tr>
      
    <tr> <td><bean:message key="user.renewpwd"/> </td>
    <td> <html:password property="renewpwd"/></td></tr>
  
   <tr>   <td align="center"> <html:submit/></td>   <td align="center">  <html:cancel/></td></tr>
         
      </table>  
     </html:form>
   </center>
    </body>
</html>





From the above  "changePwd.jsp"  page to   control jumping to  "sessionexpired.jsp"

.
"sessionexpired.jsp" code      :

<%@page import="com.client.form.UserDataForm"%>
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%
    UserDataForm userData = (UserDataForm)request.getSession(false).getAttribute("UserData");
    if (userData == null) {
        userData = new UserDataForm();
        userData.setLastmsg("Session Expired! Please login again");          // Setting the values into bean

        String s2=userData.getLastmsg();              //we are getting the sessionExpiration message  from the  Userdata bean and printing on browser.
        %>
 <%=s2%>              // It is used print the message on browser.
<%
}
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'sessionexpired.jsp' starting page</title>
   
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
   

  </head>
 
   <body>
 
  

 <br>
  </body>
 
</html>

                         ----------------------End----------------------------------

                        -------------------Wishing you all the Best------------








Pagination code to Limit the Page number by using javascript

   HI ,

     This example explains how to write an application using HTML  and JAVASCRIPT  which uses pagination to display the results with Limited  indexing.


 what is pagination?

         Fetching millions of records from database consumes almost all CPU power and memory of machine.

         Hence we break millions of records into small chunks showing limited number of records (say 20 or 30) per page. The best example of this is Google search pagination which allows user to navigate to next page by page number and explore limited records per pages.


Source code of  the Pagination to fix the number of records...

Save this file with anyname.html

 <table>
        <tr>
          <td><label id="lDisplayPerPg" for="lDisplayPerPg">Reports per page</label>
            <select name="listDisplayPerPg" id="listDisplayPerPg">
              <option value="2" selected="selected">2</option>
              <option value="4">4</option>
              <option value="6">6</option>
              <option value="8">8</option>
            </select></td>
        </tr>
      </table>


          <form method="post" action="">
            <table id="tadminViewReport" border="0" width="960px" cellpadding="0" cellspacing="0">
              <tr>
                <th width="15%">Username</th>
                <th width="15%">Report ID</th>
                <th width="40%">Report Title</th>
                <th width="20%">Date submitted</th>
                <th width="10%">Status</th>
              </tr>

              <tr>
                <td>username1</td>
                <td>reportID1</td>
                <td class="reportDoc">Document 1</td>
                <td>Date 1</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username2</td>
                <td>reportID2</td>
                <td class="reportDoc">Document 2</td>
                <td>Date 2</td>
                <td><a href="admin_report_details.html">In Queue</a></td>
              </tr>
              <tr>

                <td>username3</td>
                <td>reportID3</td>
                <td class="reportDoc">Document 3</td>
                <td>Date 3</td>
                <td><a href="admin_report_details.html">Completed</a></td>
              </tr>

              <tr>
                <td>username4</td>
                <td>reportID4</td>
                <td class="reportDoc">Document 4</td>
                <td>Date 4</td>
                <td><a href="admin_report_details.html">In Queue</a></td>
              </tr>

              <tr>
                <td>username5</td>
                <td>reportID5</td>
                <td class="reportDoc">Document 5</td>
                <td>Date 5</td>
                <td><a href="admin_report_details.html">In Queue</a></td>
              </tr>

              <tr>
                <td>username6</td>
                <td>reportID6</td>
                <td class="reportDoc">Document 6</td>
                <td>Date 6</td>
                <td><a href="admin_report_details.html">Completed</a></td>
              </tr>

              <tr>
                <td>username7</td>
                <td>reportID7</td>
                <td class="reportDoc">Document 7</td>
                <td>Date 7</td>
                <td><a href="admin_report_details.html">Completed</a></td>
              </tr>

              <tr>
                <td>username8</td>
                <td>reportID8</td>
                <td class="reportDoc">Document 8</td>
                <td>Date 8</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username9</td>
                <td>reportID9</td>
                <td class="reportDoc">Document 9</td>
                <td>Date 9</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username10</td>
                <td>reportID10</td>
                <td class="reportDoc">Document 10</td>
                <td>Date 10</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

                <tr>
                <td>username11</td>
                <td>reportID11</td>
                <td class="reportDoc">Document 11</td>
                <td>Date 11</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

                <tr>
                <td>username12</td>
                <td>reportID12</td>
                <td class="reportDoc">Document 12</td>
                <td>Date 12</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

                <tr>
                <td>username13</td>
                <td>reportID13</td>
                <td class="reportDoc">Document 13</td>
                <td>Date 13</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

                <tr>
                <td>username14</td>
                <td>reportID14</td>
                <td class="reportDoc">Document 14</td>
                <td>Date 14</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

 <tr>
                <td>username15</td>
                <td>reportID15</td>
                <td class="reportDoc">Document 15</td>
                <td>Date 15</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

               <tr>
                <td>username16</td>
                <td>reportID16</td>
                <td class="reportDoc">Document 16</td>
                <td>Date 16</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

               <tr>
                <td>username17</td>
                <td>reportID17</td>
                <td class="reportDoc">Document 17</td>
                <td>Date 17</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

             

              <tr>
                <td>username18</td>
                <td>reportID18</td>
                <td class="reportDoc">Document 18</td>
                <td>Date 18</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username19</td>
                <td>reportID19</td>
                <td class="reportDoc">Document 19</td>
                <td>Date 19</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username20</td>
                <td>reportID20</td>
                <td class="reportDoc">Document 20</td>
                <td>Date 20</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username21</td>
                <td>reportID21</td>
                <td class="reportDoc">Document 21</td>
                <td>Date 21</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>


           <tr>
                <td>username22</td>
                <td>reportID22</td>
                <td class="reportDoc">Document 22</td>
                <td>Date 22</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>
   
     <tr>
                <td>username23</td>
                <td>reportID23</td>
                <td class="reportDoc">Document 23</td>
                <td>Date 23</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>



     <tr>
                <td>username24</td>
                <td>reportID24</td>
                <td class="reportDoc">Document 24</td>
                <td>Date 24</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>

              <tr>
                <td>username25</td>
                <td>reportID25</td>
                <td class="reportDoc">Document 25</td>
                <td>Date 25</td>
                <td><a href="admin_report_details.html">Received</a></td>
              </tr>


            </table>
            <div id="pageNavPosition" align="center"></div>
            <br />
          </form>

          <center>

          <script type="text/javascript"  ><!--
           reportsPerPage = listDisplayPerPg.options[listDisplayPerPg.selectedIndex].value;

           var pager = new Pager('tadminViewReport', reportsPerPage);
       
           pager.init();
           pager.showPageNav('pager', 'pageNavPosition');
           pager.showPage(1);
      


function Pager(tableName, itemsPerPage) {

   this.tableName = tableName;
   this.currentPage = 1;
   this.pages = 0;
   this.inited = false;

   this.showRecords = function(from, to) {       
       var rows = document.getElementById(tableName).rows;
       // i starts from 1 to skip table header row
       for (var i = 1; i < rows.length; i++) {
           if (i < from || i > to) 
               rows[i].style.display = 'none';
           else
               rows[i].style.display = '';
       }
   }

   this.showPage = function(pageNumber) {
           
       if (!this.inited)
       {
        alert("not inited");
        return;
       }

       var oldPageAnchor = document.getElementById('pg'+this.currentPage);
       oldPageAnchor.className = 'pg-normal';

       this.currentPage = pageNumber;
       var newPageAnchor = document.getElementById('pg'+this.currentPage);
       newPageAnchor.className = 'pg-selected';
              
       var from = (pageNumber - 1) * Number(itemsPerPage) + 1;
       var to = (from + Number(itemsPerPage)) - 1;
       this.showRecords(from, to);
       
       
       var pgNext = document.getElementById(this.pagerName + 'pgNext');

       var pgPrev = document.getElementById(this.pagerName + 'pgPrev');

       if (pgNext != null) {
           if (this.currentPage == this.pages) pgNext.style.display = 'none';
           else pgNext.style.display = '';
       }
       if (pgPrev != null) {
           if (this.currentPage == 1) pgPrev.style.display = 'none';
           else pgPrev.style.display = '';
       }
   } 
  
   this.prev = function() {
       if (this.currentPage > 1)
       {
           this.createPager(this.currentPage-4,this.currentPage); // it  used to move the cursor to privious index.
           this.showPage(this.currentPage - 1);
        }  
   }

   this.next = function() {
       if (this.currentPage < this.pages)
       {
    this.createPager(this.currentPage,this.currentPage+4);  //when i click the next button it is count the records      upto 5 . So indexing   is mainting the standed.

    this.showPage(this.currentPage + 1);  //it is used to print  imediate next records.
   
   
       }
   }                       

     this.init = function()
       { 
       var rows = document.getElementById(tableName).rows;
   

       var records = (rows.length - 1);
       this.pages = Math.ceil(records / itemsPerPage);
   
       this.inited = true;
   }



//it is used to  move the cursor upto 5 records.
    this.createPager = function(startEle,EndEle){
   
   
if(EndEle<=this.pages && startEle>0)
{
     var pagerName = 'pager';




var pagerHtml = ' <span id="' + pagerName + 'pgPrev" onclick="' + pagerName + '.prev();" class="pg-normal">   &#171 Prev  </span> &nbsp; ' ;    


var element = document.getElementById('pageNavPosition');     
for (var page = startEle; page <= EndEle; page++)
 

   pagerHtml += ' <span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + ' </span> &nbsp; ';          ;

  
    pagerHtml += ' <span id="' + pagerName + 'pgNext" onclick="'+ pagerName+'.next();" class="pg-normal"> Next &#187;</span> '; 
                                
      element.innerHTML = pagerHtml;
   
        }
   
    }

   this.showPageNav = function(pagerName, positionId) {
   
       if (! this.inited) {
           alert("not inited");
           return;
       }

  var element = document.getElementById(positionId);
  
   var pagerHtml = ' <span id="' + pagerName + 'pgPrev" onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> &nbsp;  ';
   

       var totPages;  //for printing number of indexes per page
     
       if(this.pages >=5 )
       {
          // alert("pages value"+this.pages);
            totPages = 5
       }
       else
       {
      totPages = this.pages;
       }

       //it is used to print the  fixed 5 records.

  for (var page = 1; page <= totPages; page++)
     

           pagerHtml += ' <span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '  </span> &nbsp;';

       pagerHtml += ' <span id="   '   + pagerName + 'pgNext" onclick="'+ pagerName+'.next();" class="pg-normal"> Next &#187;</span> ';    
   
       element.innerHTML = pagerHtml;

   }
}
</script>
</center>

<style>
.pg-normal, .pg-selected{
    cursor:pointer;
    text-align: center;

}
.pg-selected{
    color:blue;
    text-align: center;
   
}
</style>





-------------------------------@-----------------------------------------@----------------------


    Wishing you All The Best-