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------------








No comments:

Post a Comment