Domanda

Our application requires users to be logged in to view any content. Access to all pages is intercepted by LoginInterceptor which brings up the login form if there's no valid session for the user.

I'd like the interceptor to remember the original request URI before displaying the login form and redirect to it if the login form validation is successful.

I tried to follow Struts 2 Redirect to correct action after authentication interceptor.

@Service
@Results({
    @Result(name = "redirect", type = "redirect", location = "${savedUrl}")
})
public class LoginInterceptor extends AbstractInterceptor {
    //...
    private String savedUrl;
    //...
    @Override
    public final String intercept(final ActionInvocation invocation) throws Exception {
       // ...
       savedUrl = (String) session.getAttribute("savedUrl");
       // ...
       if (processLogin(request, session)) { // validate login form
           if (!StringUtils.isEmpty(savedUrl)) {
              return "redirect";
           }
           return LOGIN_SUCCESS_RESULT;
       }
       // if there's no loginData in sesssion, remeber the URI and display a login form
       String queryString = request.getQueryString();
       session.setAttribute("savedUrl", request.getRequestURI() + (queryString==null ? "" : ("?" + queryString)));
       return "login";
    }
    // ...
    public String getSavedUrl(){
       return savedUrl;
    }
}

However I get a blank page as a result of return "redirect". getSavedUrl() is never called.

Solution:

Scratch the @Results annotation completely and instead of return "redirect"; call

response.sendRedirect(savedUrl); return null;
È stato utile?

Soluzione

If not logged in then redirect to LOGIN result. Then you should rewrite your interceptor something like

public final String intercept(final ActionInvocation invocation) throws Exception {
   // before save original url
   Map session = invocation.getInvocationContext().getSession();
   Object action = invocation.getAction();
   if (!(action instanceof LoginAction)){ 
     String queryString = request.getQueryString();
     session.put("savedUrl", request.getRequestURI()+(queryString==null?"":("?"+queryString)));
   } else {
     return invocation.invoke();
   }

   if (!processLogin(request, session)) { //return false if not authenticated
     session.put("isLogin", true);
     return Action.LOGIN;
   } else {
       savedUrl = (String) session.get("savedUrl");
       boolean isLogin = (boolean)session.get("isLogin");
       if (!StringUtils.isEmpty(savedUrl) && isLogin) {
          session.put("isLogin", false); 
          return "redirect";
       }
       return invocation.invoke();
   }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top