1. 程式人生 > >shiro登入成功後,沒有跳轉到Success

shiro登入成功後,沒有跳轉到Success

debug後跟進去觀察後發現FormAuthenticationFilter成功登陸後,會呼叫它的onLoginSuccess方法。

  protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        issueSuccessRedirect(request, response);
        //we handled the success redirect directly, prevent the chain from continuing:
        return false;
    }



 protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());
    }

 public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl)
            throws IOException {
        String successUrl = null;
        boolean contextRelative = true;
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
            successUrl = savedRequest.getRequestUrl();
            contextRelative = false;
        }

        if (successUrl == null) {
            successUrl = fallbackUrl;
        }

        if (successUrl == null) {
            throw new IllegalStateException("Success URL not available via saved request or via the " +
                    "successUrlFallback method parameter. One of these must be non-null for " +
                    "issueSuccessRedirect() to work.");
        }

        WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
    }

可以看出如果由之前的頁面跳轉到登陸頁的話,savedRequest儲存了原來的地址,這個地址會取代我們設定的successUrl;只有當savedRequest為null的時候,successUrl才會是我們設定的地址。

怎麼避免返回原來的頁面,按照我們設定的successUrl跳轉呢?重寫它

  //重寫onSSOLoginSuccess,實現追加自定義引數
  protected boolean onSSOLoginSuccess(UsernamePasswordCaptchaToken token, Subject subject, ServletRequest request,
			ServletResponse response, String accessToken) {
		try {

			String b = request.getParameter("hidCurrBrand");
			if (b != null) {
				String sucurl = this.getSuccessUrl();
				if (sucurl.contains("?")) {
					sucurl = sucurl.substring(0, sucurl.indexOf("?"));
				}
				sucurl += "?brand=" + b + "&accessToken=" + accessToken;
				System.out.println("this successUrl:" + sucurl);
				this.setSuccessUrl(sucurl);
			}
			//重寫issueSuccessRedirect方法,解決successUrl被覆蓋的問題
			issueSuccessRedirect(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}


	//重寫issueSuccessRedirect,直接跳轉我們設定的SuccessUrl
	@Override
	protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
		WebUtils.issueRedirect(request, response, this.getSuccessUrl(), null, true);
	}