Struts2从登录拦截器重定向

时间:2014-01-08 10:56:32

标签: java login struts2 interceptor actionresult

我们的应用程序要求用户登录才能查看任何内容。 LoginInterceptor拦截对所有页面的访问,如果用户没有有效会话,则会显示登录表单。我希望拦截器在显示登录表单之前记住原始请求URI,并在登录表单验证成功时重定向到它。我试图关注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;
    }
}

然而,由于return "redirect",我得到一个空白页面。永远不会调用getSavedUrl()

解决方案:完全抓取@Results注释,而不是return "redirect";调用response.sendRedirect(savedUrl); return null;

1 个答案:

答案 0 :(得分:3)

如果未登录,则重定向到LOGIN结果。然后你应该重写像

这样的拦截器
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();
   }
}