2016-04-25 221 views
2

我想在spring mvc方法中重定向到另一個.jsp。我不想使用JavaScripts方法,如:window.location.replace(url)。Spring MVC:在@ResponseBody中重定向

我的方法:

@RequestMapping(value= "loginUser", method=RequestMethod.POST) 
public @ResponseBody String loginUser (@RequestParam("name") String name, @RequestParam("password") String password){ 

    return ""; 
} 

回答

2

當您的請求需要json響應時,您無法從Spring重定向。您可以設置重定向的參數,以便當您輸入成功塊時,可以使用window.location.reload();檢查參數以重定向。例如,從一個類似的帖子,看看這個答案,

Redirect on Ajax Jquery Call

一個想法是讓瀏覽器知道它應該由 重定向添加一個重定向變量來生成的對象和檢查 它在JQuery中

$(document).ready(function(){ 
    jQuery.ajax({ 
     type: "GET", 
     url: "populateData.htm", 
     dataType:"json", 
     data:"userId=SampleUser", 
     success:function(response){ 
      if (response.redirect) { 
       window.location.href = response.redirect; 
      } 
      else { 
       // Process the expected results... 
      } 
     }, 
    error: function(xhr, textStatus, errorThrown) { 
      alert('Error! Status = ' + xhr.status); 
     } 

    }); 
}); 

您也可以添加一個響應頭用於重定向像response.setHeader("REQUIRES_AUTH", "1")和jQuery的成功,

success:function(response){ 
     if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
      window.location.href = 'login.htm'; 
     } 
     else { 
      // Process the expected results... 
     } 
    } 

請參考類似的問題:Spring Controller redirect to another page

+0

如果使用了@ @ ResponseBody,那麼這個工作是否可行? – OrangeDog

+0

@OrangeDog似乎也不能工作。重定向到json請求上的另一個頁面更新替代解決方案 – Lucky

+0

誰說這是一個異步請求 – OrangeDog

1

包括HttpServletResponse參數並調用sendRedirect(String)

或者,根本不使用@ResponseBody,並返回要使用的模型/視圖。

+0

是@ResponseBody在我的情況下必不可少的,包括我的HttpServletResponse的,並呼籲的sendRedirect(字符串),並忽略了最低的工作。 :( –

+0

你確定這很重要嗎?當這個電話沒有重定向時,你會返回什麼? – OrangeDog