Friday, 22 March 2013

How to set session and destroy session and setInactive time of session in jsp

1)Set the session
<%
String uname="ishwar";
session.setAttribute("name",uname);
%>

2)read the value of session and if user is not login then redirect to login.jsp page
<%
if(session.getAttribute("name")==null)
{
    out.println("<script>alert('please login first')</script>");
    out.println("<script>location.href='login.jsp'</script>");
   
}
else
{
    String uname=(String)session.getAttribute("name");
    out.println("uname is"+uname);
}
%>

3)Destroy or Delete the session
<%
    session.invalidate();
%>

4)set inactive time for session

for programmatically set session
This for 10 seconds
<% session.setMaxInactiveInterval(10); %>

This will set your session to keep everything till the browser is closed
<% session.setMaxInactiveInterval(-1); %>

This should set it for 1 day
<% session.setMaxInactiveInterval(60*60*24); %>

Other way you can set inactive time for session in web-inf file
<web-app>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>

No comments:

Post a Comment