2010-09-27 45 views
3

當前我使用request.setAttribute()和request.getAttribute()作爲將對象從處理程序攔截器傳遞給控制器​​方法的一種方法。我不認爲這是一種理想的技術,因爲它要求我將HttpServletRequest作爲我的控制器方法的參數。 Spring很好地隱藏了控制器的請求對象,所以除了這個目的,我不需要它。Spring Web MVC:將處理程序攔截器中的對象傳遞給控制器​​?

我嘗試使用@RequestParam註釋與我在setAttribute()中設置的名稱,但當然這並不工作,因爲請求屬性不是請求參數。據我所知,沒有用於屬性的@RequestAttribute註解。

我的問題是,是否有更好的方法將攔截器中的對象轉交給控制器方法,而不訴諸將其設置爲請求對象上的屬性?

回答

0

爲了節省訪問此頁面的人的時間:自Spring 4.3 @RequestAttribute註釋是Spring MVC的一部分,因此不需要創建自己的@RequestAttribute註釋。

0

使用攔截器prehandle方法和會話是這樣的:

攔截:

@Override 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
    if (!(handler instanceof HandlerMethod)) { 
     return true; 
    } 
    HttpSession session = request.getSession(); 
    String attribute = "attribute"; 
    session.setAttribute("attributeToPass", attribute); 
    return true; 
} 

控制器:

@RequestMapping(method = RequestMethod.GET) 
public String get(HttpServletRequest request) { 
    String attribute = (String)request.getSession().getAttribute("attribteToPass"); 
    return attribute; 
} 
+0

不會將它添加到會話中,使得在控制器返回時,spring會在響應中將數據返回給客戶端? – andreasm 2018-01-09 15:35:39

相關問題