Showing posts with label Struts 2. Show all posts
Showing posts with label Struts 2. Show all posts

Tuesday, June 24, 2014

To check the existence of session before doing any operation in Struts 2 application, we can use interceptor. For implementation of this, we will have to follow some easy steps:

Step 1: Make an interceptor class as below:

public class LoginInterceptor extends AbstractInterceptor {
      @Override
       public String intercept(final ActionInvocation invocation) throws Exception {
        Map session = ActionContext.getContext().getSession();

        UserVo userVo = (UserVo) session.get(Constant.LOGGEDIN_USER_KEY);
        String userLoggedin="";
        if(userVo!=null){
            userLoggedin = userVo.getUsername();

        }
        Object action = invocation.getAction();
        // user is not logged in yet
        if(userLoggedin == null||userLoggedin.equals("")){      

            // Pages that require the user to be logged in - user not logged in yet
            if (!(action instanceof BaseAction)) {
                 return "loginRedirect";
            }      
        }
        // user is logged in
        else{
             return invocation.invoke();
        }
        return invocation.invoke();
    }
}


Step 2: In struts.xml configuration file, add in the package of

 
<interceptors> <interceptor name='login' class='com.dbbl.mbs.portal.auth.LoginInterceptor'> 
 </interceptor> <interceptor-stack name='loginStack'> 
 <interceptor-ref name='login'>
</interceptor-ref> 
<interceptor-ref name='defaultStack'>
</interceptor-ref> 
</interceptor-stack> 
</interceptors> 
<default-interceptor-ref name=&quot;loginStack&quot; /> 
 <global-results> 
<result name=&quot;loginRedirect&quot; type=&quot;redirect&quot;>/login.jsp</result> 
</global-results>


That's the start of the epic.