簡體   English   中英

在簽名中沒有RedirectAttributes的方法中訪問RedirectAttributes

[英]Accessing RedirectAttributes in method without RedirectAttributes in signature

是否可以在簽名中沒有RedirectAttributes的方法中訪問RedirectAttributes? 例如,當覆蓋以下方法時:

@Override
public void onAuthenticationSuccess(final HttpServletRequest req, final HttpServletResponse res,
        final Authentication auth) throws IOException, ServletException {

    // add something to RedirectAttributes here
    // redirectAttributes.addFlashAttribute("attr", "value");

    super.onAuthenticationSuccess(req, res, auth);
}

我正在使用Spring 3.2.2.RELEASE。

如您在DispatcherServlet類實現中所看到的,有常量:

public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";
public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP";
public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";

Spring有一個名為RequestContextUtils的類,該類具有以下方法:

public static Map<String, ?> getInputFlashMap(HttpServletRequest request)
public static FlashMap getOutputFlashMap(HttpServletRequest request)    
public static FlashMapManager getFlashMapManager(HttpServletRequest request)

前兩種方法將使您分別訪問輸入和輸出Flash映射。 最后一個方法返回FlashMapManager,它具有許多方便的方法來處理Flash屬性。 有關詳細信息,請參見此接口的實現,尤其是AbstractFlashMapManager。

如果您的目標是“添加表明客戶已首次進入主頁的指示”,則HttpSession可以解決這個問題:

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException
{
    ...
    boolean firstLogin = <determine whether this is the first login>;
    <reset condition that caused firstLogin to be true>;
    ...
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.setAttribute("firstLogin", firstLogin);
    }
    else {
        log.debug("No session");
    }
}

// Controller for some page
@RequestMapping(value = <your page>, method = RequestMethod.GET)
public String showPage(<some other args>, HttpSession session)
{
    ...
    Object firstLogin = session.getAttribute("firstLogin");
    Assert.isInstanceOf(Boolean.class, firstLogin, "firstLogin");
    if ((Boolean)firstLogin) {
        <handle first login>;
    }
    ...
    return <page>;
}

這對我有用。 其背后的邏輯是登錄是在整個會話(可能包括多個請求)的上下文中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM