2016-09-21 71 views
0

我已經設置了一個Spring HandlerInterceptor來向HttpServletRequest添加一個屬性,以便能夠從Controller讀取它,可悲的是,這看起來並不起作用,這對我來說似乎很奇怪。我做錯了什麼?任何想法如何將數據從攔截器傳輸到控制器?Spring 3 HandlerInterceptor將信息傳遞給控制器​​

下面是兩個影響類

public class RequestInterceptor implements HandlerInterceptor { 
    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { 
     request.setAttribute("my-role", "superman"); 
    } 
    [...] 
} 

@RestController 
@RequestMapping("Test") 
public class TestController { 
    public final Logger logger = LoggerFactory.getLogger(getClass()); 

    @RequestMapping(value = "something") 
    public void something(HttpServletRequest request) { 
     logger.info(request.getAttribute("my-role")); 
    } 

    [...] 
} 

的request.getAttribute(「我的角色」)返回null的簡化代碼...但如果我在讀的postHandle它返回的值除外的HandlerInterceptor,我覺得我失去了一些東西...

編輯:我發現通過會議與「request.getSession()。setAttribute」作爲一種魅力,仍然我不明白爲什麼請求本身在這個用例中不起作用。

+0

發佈您的所有攔截器代碼 – george

回答

0

你可以嘗試會議而不是像下面的請求。

public boolean preHandle(HttpServletRequest request, 
       HttpServletResponse response, Object handler) throws Exception { 
       ... 
       HttpSession session = request.getSession(); 
       session.setAttribute("attributeName", objectYouWantToPassToHandler); 
       .... 
       } 
    In your handler handleRequest method: 

     public ModelAndView handleRequest(HttpServletRequest request, 
      HttpServletResponse response) throws Exception {     

      .... 
      HttpSession session = request.getSession(); 
      objectYouWantToPassToHandler objectYouWantToPassToHandler = session.getAttribute("attributeName"); 
      .... 


    } 
+0

是的,它的工作原理,但我不明白爲什麼請求級別不起作用。 – JavaCupiX

相關問題