0

How to set session timeout in Struts 2:

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = 1L;

    @Override
      public String intercept(ActionInvocation invocation) throws Exception {
          Map<String,Object> session = invocation.getInvocationContext().getSession();
          if(session.isEmpty())
              return "session";
          return invocation.invoke();
      }
}

it's not working.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 1
    In web.xml (likely preferred) or using HttpSession#setMaxInactiveInterval like most other Java web frameworks? I'm not sure what you mean by "it doesn't work" since there's no code here that checks for session validity. – Dave Newton Jun 29 '23 at 14:40

1 Answers1

0

This code you can use in interceptor:

HttpServletSession httpsession = invocation.getInvocationContext().getServletRequest().getSession();
httpsession.setMaxInactiveInterval(timeout);

You can read more about setting a timeout to http session:

Difference between setting session timeouts using web.xml and setMaxInactiveInterval

The first approach is using a static constant in the configuration for all sessions. The second approach is dynamic where you can set the value using servlet API at runtime dynamically and affected only a session which method is called. Once the value is set the session is invalidated by the container regardless which approach is used. See what the doc says about HttpSession#setMaxInactiveInterval(int):

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

An interval value of zero or less indicates that the session should never timeout.

The value in deployment descriptor web.xml is in “minutes”, but the setMaxInactiveInterval() method accepts the value in “seconds”.

Roman C
  • 49,761
  • 33
  • 66
  • 176