How to resolve session timeout issue in JAVA

How to fixed Session timeout issue  :-    
Pls follow the below details.............................

SessionTimeOut.jsp
---------------------------------
<%@page import="com.ecw.security.DataValidation"%>
<%@page import="com.ecw.components.PerformanceHelper"%>
<%
String sessionValueinSeconds =  PerformanceHelper.checkItemkeyCache(null, "sessionTimeOut");
%>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
<script src="../../script/newui/js/jquery-1.10.2.min.js"></script>

<script>
    $(document).ready(function()       
    {
    /* session Timeout code End Pavan */
    var timer = null;
    var secondsBeforeExpire='<%=DataValidation.escapeStringForJavaScript(sessionValueinSeconds)%>';
    if(secondsBeforeExpire!="")
    {
    var warnBeforeMinutes = 5*60*1000;
    var modalClock= warnBeforeMinutes;
    var triggerWarn = (secondsBeforeExpire * 1000 - warnBeforeMinutes);
    var timerSessionAlive = null;
    var sessionalivetimer= triggerWarn-60*1000;
    var sessiondialoguetimer = null;
    timerSessionAlive = setTimeout(keepSessionAlive,1000);
     function userActive(event) {
      if ($(event.target).is('#sessionModal, #sessionModal *')) {
          return;
      }
       if(!timerSessionAlive){                   
          timerSessionAlive = setTimeout(keepSessionAlive,(sessionalivetimer-timer));                   
      }
      clearTimeout(timer);
      timer = setTimeout(userIdle,triggerWarn);
    }
    function logOutonIgnore() {
      $('.modal').modal('hide');
      $("#signOut").trigger('click');
    }
       function keepSessionAlive() {
      clearTimeout(timerSessionAlive);
      timerSessionAlive= null;
      $.ajax({
          type : "POST",
          url : "../../HealthRecShareTrans?action=extendSession"         
      });
    }
   
       function userIdle() {
          
      $("#sessionContent").html("");
      $("#sessionContent").append('<%=resourcebundle.getString("SessionIsGoingToExpireIn")%>'+" <b><font color='red'><span id='Dialoguecounter'>"  
              + modalClock/(1000*60)
              + "</span></font></b> "+'<%=resourcebundle.getString("Minutes") %>'+"<br/>"+'<%=resourcebundle.getString("PleasePress") %>'+" '<b>"+'<%=resourcebundle.getString("ContinueBrowsing") %>'+"</b>' "+'<%=resourcebundle.getString("ToAvoidSessionExpiration") %>');
      $("#sessionModal").modal(
      {
          backdrop : 'static',
          keyboard : false
      });
      sessiondialoguetimer = setInterval(decrementCounter,1*60*1000);
    }
     function decrementCounter(){
      if(modalClock > 60000){
          modalClock = modalClock- 60000;
          $("#Dialoguecounter").html(modalClock/(1000*60));
      }else{
          modalClock= warnBeforeMinutes;
          clearInterval(sessiondialoguetimer);
          logOutonIgnore();
      }
    }
   
    $('*').bind('keydown', function (event){
      userActive(event);})
    .bind('DOMMouseScroll', function (event){
      userActive(event);})
    .bind('mousewheel', function (event){
      userActive(event);})
    .bind('mousedown', function (event){
      userActive(event);})
    $(window).bind("load",  function (event){
      userActive(event);})
     
    $("#continue").click(function() {
      clearInterval(sessiondialoguetimer);
      modalClock= warnBeforeMinutes;
      triggerWarn = (secondsBeforeExpire * 1000 - warnBeforeMinutes);
      clearTimeout(timer);//reset the timer
      timer = setTimeout(
      userIdle,
      triggerWarn);//again post pone user Idle function
      $.ajax({
          type : "POST",
          url : "../../HealthRecShareTrans?action=extendSession"         
      });
      $('.modal').modal('hide');
    });
    }
/* session Timeout code End Pavan */

    });
</script>
<div class="modal fade" id="sessionModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-dialog"  style="margin-top: 10%;">
         <div class="modal-content">        
             <div class="modal-body">
                 <p id="sessionContent"></p>
             </div>
             <div class="modal-footer">
                 <button type="button" class="btn orngBtn" data-dismiss="modal" style="margin-right: 10px;" id="continue"><%=resourcebundle.getString("ContinueBrowsingButton")%></button>
                 <a style="font-size: 16px;" class="pull-right" onclick="javascript:window.location.href='../../HealthRecShareTrans?action=userLogout'"
                    href="#">
                     <button type="button" class="btn btn-listbtn" data-dismiss="modal"
                             style="margin-right: 10px;" id="signOut"><%=resourcebundle.getString("LogOutSession")%>
                     </button>                   
                 </a>
             </div>
         </div>
     </div>
 </div>
 </body>
</html>


-------------------------------------------------------------------------------------------------------
Servlet
HealthRecShareTrans.java
--------------------------------------------------------------------
package com.ecw.webservices;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ecw.util.CwXmlHelper;
import com.ecw.util.Util;

/**
 * Servlet implementation class HealthRecShareTrans
 */
public class HealthRecShareTrans extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HealthRecShareTrans() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Document oDoc;
        InputStream tranResponseXml;//="";
        String responseXml = "";
        String action = "";

        String statusCode ="",status = "", extrefid = "";
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String result = "";
        try
        {

            CCR2CCDClient ccrClient = new CCR2CCDClient();
            tranResponseXml = request.getInputStream();//("response");

            StringBuffer xmlStr=new StringBuffer();
            int d;
            while((d=tranResponseXml.read()) != -1){
                xmlStr.append((char)d);
            }
            responseXml = xmlStr.toString();
            if(responseXml!=null)
                responseXml=responseXml.trim();
            action = request.getParameter("action");
           
            if("transAck".equalsIgnoreCase(action)){
                if(responseXml!=null && responseXml.length() > 0){
                    oDoc = CwXmlHelper.getXmlDocument(responseXml);           
                    NodeList oResponses = oDoc.getElementsByTagName("referralResponse");
                    for (int i = 0; i < oResponses.getLength(); i++) //for each requested availability
                    {
                        Node oNode = oResponses.item(i);
                        statusCode =CwXmlHelper.getChildTagValue(oNode, "statusCode");               
                        status = CwXmlHelper.getChildTagValue(oNode, "status");
                        extrefid = oNode.getAttributes().item(0).getNodeValue();
                        result = ccrClient.update_trancStatus(Integer.parseInt(extrefid),status,statusCode);

                    }
                    if("success".equalsIgnoreCase(result)){
                        out.print("ACK");
                    }else{
                        Util.Log("Failed on Portal due to some reason");
                    }
                }
            }else if("GetShareLogs".equalsIgnoreCase(action)){
                String strUid= request.getParameter("uid");
                int nUid = 0;
                if(strUid!=null){
                    try{
                        nUid = Integer.parseInt(strUid);
                    }catch(Exception e){
                        nUid = 0;
                    }
                    if(nUid > 0 ){
                        String page = request.getParameter("page");
                        String limit = request.getParameter("rows");
                        String sColName = request.getParameter("sidx");
                        String sSortOrder = request.getParameter("sord");
                       
                        result = ccrClient.getShareLogs(nUid,page,Integer.parseInt(limit),sColName,sSortOrder);
                    }
                   
                    response.setContentType("application/json;charset=UTF-8");
                    out.print(result);
                }
            }else if("GetLogs".equalsIgnoreCase(action)){
                HttpSession session = request.getSession();
                //String strUid = (String)session.getAttribute("uid");
               
                int nUid = 0;
                if(session.getAttribute("uid")!=null){
                    nUid = (Integer)session.getAttribute("uid");
                }
                if(nUid > 0 ){
                    String page = request.getParameter("page");
                    String limit = request.getParameter("rows");
                    String sColName = request.getParameter("sidx");
                    String sSortOrder = request.getParameter("sord");
                   
                    result = ccrClient.getLogs(nUid,page,Integer.parseInt(limit),sColName,sSortOrder);
                }
                   
                    response.setContentType("application/json;charset=UTF-8");
                    out.print(result);
               
            }//session timeout added
            else  if ("extendSession".equalsIgnoreCase(action)) {
                request.getSession().setMaxInactiveInterval(request.getSession().getMaxInactiveInterval());                  
           }
            else if("userLogout".equalsIgnoreCase(action)) {
             response.sendRedirect(request.getContextPath() + "/jsp/100mp/logout.jsp");
            }
        }catch(Exception e){
            Util.AppendExceptionToLog(e);
        }
    }

}
---------------------------------------------------------------------------------------------
DATABASE
---------------
name                name  value  supportRemark   
sessionTimeOut      0      1800   sessionTimeOut
---------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

Blog gives you enthusiasm,zeal

How to encode HTML in JAVA (Remove HTML from your text)