2016-08-08 20 views
0

我有一個控制器@ResponseBody註釋。我想要做的是,如果這個用戶不存在處理用戶的ID並返回一個JSON對象。如果存在用userInfo重定向到用戶頁面。下面的代碼給出了Ajax錯誤。有沒有辦法用userInfo重定向到用戶頁面?如何從spring ajax控制器重定向?

@RequestMapping(value = "/user/userInfo", method = {RequestMethod.GET}) 
    @ResponseBody 
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) { 

     if(...){ 
      .....//ajax return 
     }else{ 
      modelMap.addAttribute("userInfo", userInfoFromDB); 
      return "user/user.jsp"; 
     } 

    } 
+0

你有沒有試過返回「重定向:/user/user.jsp」? –

+0

@AndreasBrunnet我想用ModelMap屬性重定向。 – hellzone

+0

選中此:http://stackoverflow.com/questions/36840104/spring-mvc-redirect-in-responsebody – Blank

回答

2

那麼,這種方法是用@ResponseBody註釋。這意味着String返回值將是響應的主體。所以在這裏,你只是返回"user/user.jsp"來電。

由於您可以完全訪問響應,因此您總是可以明確地使用response.sendRedirect(...);進行重定向。甚至有可能明確地要求Spring通過flash作爲RedirectAttribute傳遞userInfoFromDB。你可以從我看到更多關於this other answer的細節(後者用於攔截器,但可以用於控制器)。你將不得不返回null告訴spring,控制器代碼已經完全處理了響應。這將是:

... 
}else{ 
    Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request); 
    flash.put("userInfo", userInfoFromDB); 
    response.redirect(request.getContextPath() + "/user/user.jsp"); 
    return null; 
} 
... 

問題是,客戶端需要一個字符串響應,不會到達,必須做好準備。如果不是,你會得到一個錯誤的客戶端。然後另一種方法是不重定向而是通過包含URL旁邊一個特殊的字符串:

... 
}else{ 
    Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request); 
    flash.put("userInfo", userInfoFromDB); // prepare the redirect attribute 
    return "SPECIAL_STRING_FOR_REDIRECT:" + request.getContextPath() + "/user/user.jsp"); 
} 

,並讓客戶端的JavaScript代碼來處理該響應,並要求在下一個頁面。

相關問題