2014-02-13 102 views
1

我有一個Spring MVC應用程序,允許用戶通過以下電話添加/刪除收藏夾重定向POST請求:的Java Spring MVC的前/使用攔截

  • POST /api/users/123/favorites/456(添加項目456爲用戶123最喜歡的)
  • DELETE /api/users/123/favorites/456(移除項456作爲收藏用戶123)

我也想支持以下2個調用,這樣做同樣的事情(假設用戶123登錄):

  • POST /api/users/me/favorites/456
  • DELETE /api/users/me/favorites/456

我創建了一個攔截器,如下圖所示:

public class UserMeInterceptor extends HandlerInterceptorAdapter{ 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{ 
     Integer userId = AccessControlUtil.getUserId(); 
     String redirectUrl = request.getContextPath() + request.getRequestURI().replace("/me/", "/" + userId + "/"); 
     if(redirectUrl.endsWith("/me")){ 
      redirectUrl = redirectUrl.replace("/me", "/" + userId); 
     } 
     response.sendRedirect(redirectUrl); 
     response.flushBuffer(); 
     return false; 
    } 
} 

這種做法的偉大工程,但僅限於GET請求。任何方式我可以轉發/重定向POST請求並維護所有POST數據和方法類型?理想情況下,我想重複使用已定義來處理的情況下,當ID在傳遞同一個控制器。

回答

4

怎麼樣這種方法:

@RequestMapping("/api/users/{userId}/favorites/{favoriteId}") 
public String clientsByGym(@PathVariable("userId") String userId, @PathVariable("favoriteId") Long favoriteId) { 
    Integer theUserId = null; 
    if("me".equals(userId)) { 
     theUserId = AccessControlUtil.getUserId() 
    } else { 
     theUserId = Integer.valueOf(userId); 
    } 
    ... 
} 

基本上,有你的方法接受字符串帳戶及從那裏你可以計算出,如果它是「我」或實際用戶id值。這樣你就不必亂用重定向。如果你必須一直這樣做,你可以做一個這樣的幫手方法:

public Integer getUserId(String userId) { 
    return "me".equals(userId) ? AccessControlUtil.getUserId() : Integer.valueOf(userId); 
} 
+0

哇 - DUH!這是太棒了。無法讓自己過去用戶id爲整數的方法,但這是那麼燦爛! –

+0

@ user3285708 - 很高興我能幫助:) – SergeyB

+0

@ user3285708 - 幫我個忙,請如果你喜歡它投了答案。 – SergeyB

1

Spring MVC的有做房地產的轉換兩種機制,但這些那些不會在這種情況下,有助於清潔方法 - 檢查answer。這些並不意味着僅將selectorlly應用於特定的String參數。

最好的做法是將控件和方法應用到您想要的功能,例如請參見answer

+0

屬性轉換在這裏發揮了什麼作用? –