2015-09-29 82 views
0

我正在開發一個需要驗證表單的Spring MVC應用程序。我的問題是下一個:我想改變從我的方法返回數據的處理取決於一些邏輯。如何在運行時設置響應類型(Spring MVC)

例如,我有一個註冊用戶頁面!如果用戶字段有效,我需要在註冊頁面上向ajax發送消息。但如果它們無效,我需要返回視圖名稱(或重定向)。我該怎麼做?這裏是我的代碼:

@RequestMapping(value = "save_user", method = RequestMethod.POST) 
public String saveUser(@Valid User user, BindingResult result) { 
     if(result.hasErrors()) { 
      return "common/add_user"; // Here I need to return the view name or do redirect 
     } else { 
      userManager.add(user); 
      return "success... bla bla bla"; // Here I need to return some message. 
     } 
} 
+0

如果你不想重定向,你的控制器方法應該看起來像public @ReponseBody String saveUser(其餘部分保持不變)。如果你想重定向,請刪除responseBody。你的問題並不準確。此外,您已經在common/add中返回視圖名稱。所以,選擇一個,查看或發送給Ajax。 –

+0

感謝您的回答。是。你是對的。但我想知道我可以在運行時選擇一個(查看還是發送)?我可以根據一些邏輯選擇它嗎?也許春天有一個機制... –

+0

據我所知,沒有這樣的機制,也沒有這樣的要求,我聽說過。也許其他一些用戶可以幫助你,但我懷疑它。祝你好運。 –

回答

1

我認爲你可以這樣做:

@RequestMapping(value = "save_user", method = RequestMethod.POST) 
@ResponseBody 
public String saveUser(@Valid User user, BindingResult result) { 
     if(result.hasErrors()) { 
      return "common/add_user"; // Here I need to return the view name or do redirect 
     } else { 
      userManager.add(user); 
      return "success... bla bla bla"; // Here I need to return some message. 
     } 
} 

在你的Ajax,你可以得到響應數據

$.ajax({ 
    type: "POST", 
    url: "save_user", 
    data: $("#user").serialize(), 
    success: function(data) { 
    //get response data and process it 
    ... 
    } 
}); 

希望這有助於!

+0

這應該工作,因爲你可以根據收到的字符串重定向用戶。 –

+0

謝謝! :) 這是一個好主意!我會嘗試應用這個。 –

相關問題