Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struts 2 Session TimeOut

Tags:

java

struts2

I am new to struts. I am using Struts2. Please any one can tell me how to automatically redirect the jsp page after Session has Timeout.

like image 517
venkat Avatar asked Jan 18 '12 20:01

venkat


1 Answers

Well You need to create a way to check if the session has expired or not since Browser has no way to find out if the Session has expired or not. You need to have following steps

Define session time out in your web.xml like.

<session-config>  
        <session-timeout>  
            30  
        </session-timeout>  
    </session-config>

One of easy way around Struts2 is to create an Interceptor and check Session validity and if session has expired you can redirect user back to your specified jsp page.Here is a quick view of a sample interceptor

Interceptor

public class SessionInterceptor extends AbstractInterceptor {
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
      Map<String,Object> session = invocation.getInvocationContext().getSession();
      if(session.isEmpty())
          return "session"; // session is empty/expired
      return invocation.invoke();
  }

Finally you need to tell Stuts2 that you want to use this interceptor by declaring it in struts.xml file

struts.xml

<interceptor name="session" class="myapp.interceptor.SessionInterceptor" />
<interceptor-stack name="sessionExpirayStack">
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="session"/>
   </interceptor-stack>

Now all you need to use this stack declaration in your actions

Action Configuration

<action name="myAction" class="myClass">
    <interceptor-ref name="sessionExpirayStack" />
    <result name="success">success.jsp</result>
    <result name="session">sessionexpired.jsp</result>
  </action>

alternative you can declare a global result for *session* so that use will be redirected to the same page globally.

For way outside Struts2 you have the option to create a Servlet filter and can place you session check code inside the filter.All you need to impliment javax.servlet.Filter interface

Session Checking Filter

public final CheckSession impliments Filter{
    private FilterConfig filterConfig = null;
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        this.filterConfig = null;
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain  
            chain) {

        // Put your logic here to check session
    }
}

For Auto-redirect you have to keep on checking the session by some sort of Ajax call

like image 62
Umesh Awasthi Avatar answered Sep 24 '22 14:09

Umesh Awasthi