2012-01-03 86 views
0
public class FlashMapFilter extends OncePerRequestFilter { 

    @Override 
    @SuppressWarnings("unchecked") 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
      throws ServletException, IOException { 
     HttpSession session = request.getSession(false); 
     if (session != null) { 
      Map<String, ?> flash = (Map<String, ?>) session.getAttribute(FlashMap.FLASH_MAP_ATTRIBUTE); 
      if (flash != null) { 
       for (Map.Entry<String, ?> entry : flash.entrySet()) { 
        Object currentValue = request.getAttribute(entry.getKey()); 
        if (currentValue == null) { 
         request.setAttribute(entry.getKey(), entry.getValue()); 
        } 
       } 
       session.removeAttribute(FlashMap.FLASH_MAP_ATTRIBUTE); 
      } 
     } 
     filterChain.doFilter(request, response); 
    } 
} 

而不是每個請求顯示一次Flash消息,這會顯示一條消息,消息之前的兩個完整請求的持續時間。這是爲什麼?爲什麼我的FlashMapFilter顯示兩個請求,即使它擴展了OncePerRequestFilter?

回答

0

每個請求一次意味着doFilterInternal()將不會在單個請求中被調用兩次。要獲得更好的閃光範圍支持,請參見Spring 3.1 Using flash attributes

至於你的代碼你試過把斷點放在session.removeAttribute

1

首先確保您只在會話中設置屬性。

此外,請確保您不會呈現在會話中設置的唯一一個來自請求的設置。你如何渲染它?使用JSP EL?那麼你必須明確地使用${requestScope.flashScopeAttribute},因爲${flashScopeAttribute}也會搜索sessionScope。

相關問題