Set session value in JSP and retrieve in java class using response.sendRedirect -
am trying value session fails. value in session set in jsp page same unable retrieve in java class. please resolve:
below code snippet :
interceptor entry in servlet-context.xml file :
<interceptor> <mapping path="/**" /> <exclude-mapping path="/tabservice/pdfcreation/**"/> <beans:bean class="com.mastek.ems.filter.executetimeinterceptor"></beans:bean> </interceptor>
set session value in jsp page : index.jsp
//intiate session , set value request.getsession(true).setattribute("user", "my_user"); system.out.println("inside jsp : ssn.getattrbute : " + request.getsession(false).getattribute("user")); errorpage = false; if(!errorpage){ string encstr = "encodevalue"; response.sendredirect("http://localhost/test/index.html#detailspage?en1="+encstr); } else { requestdispatcher dispatcher = getservletcontext().getrequestdispatcher("/error.jsp"); dispatcher.forward(request, response); }
try value in interceptor : executetimeinterceptor :
system.out.println("session object:"+request.getsession(false)); // prints null system.out.println("session objectid1:"+request.getsession(false).getid()); // throws nullpointerexception long starttime = system.currenttimemillis(); if(request.getsession(false) != null){ system.out.println("inside if : ssn data:"+request.getsession(false).getattribute("user")); if( request.getsession(false).getattribute("user") != null ){ request.setattribute("starttime", starttime); system.out.println("start time::with valid session:1:"+(new simpledateformat("dd/mm/yyyy:hh:mm:ss:ssss")).format(new date(system.currenttimemillis()))); return true; } } else{ system.out.println("start time::with invalid session::"+(new simpledateformat("dd/mm/yyyy:hh:mm:ss:ssss")).format(new date(system.currenttimemillis()))); } request.setattribute("starttime", starttime); utility.setresponseerror(response, "sessiontimedout"); return false;
there chance of session getting lost when use redirect. if use redirect url, ensure 2 things.
the redirect url should same url used load current page.
also, use redirect code -
response.sendredirect(response.encoderedirecturl(your url));
check javadocs more info. https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/httpservletresponse.html#encoderedirecturl(java.lang.string)
see similar issue here - session lost , created new in every servlet request
Comments
Post a Comment