2016-11-16 99 views
2

重定向這是我更新的用戶方法:春天在POST

@ResponseBody 
@Transactional 
@RequestMapping(value = "/profile/edit/{id}", method = RequestMethod.POST) 
public String updateUser(@PathVariable("id") final Integer id, String firstname, String lastname, final RedirectAttributes redirectAttributes) { 

    respository.updateFirstname(id,firstname); 
    respository.updateLastname(id, lastname); 

    redirectAttributes.addFlashAttribute("message", "Successfully changed.."); 
    return "redirect:/profile"; 
} 

所有工作的罰款。也是數據庫中的更新。但重定向僅僅是一個字符串,不會改變路徑。有人能告訴我爲什麼嗎?

+2

刪除'@ ResponseBody'。另外,讓你的控制器交易是一個可怕的想法......你應該有一個服務是事務性的邊界(以便你可以重用那些東西)。 –

回答

4

問題出在@ResponseBody註釋中。一旦它被刪除,重定向應該按預期工作。通過使用它,您可以覆蓋Spring MVC的默認行爲,並將返回值視爲原始響應。

2

@ResponseBody仍然可以執行重定向。

你可以用下面的方法做到這一點,這使得你仍然可以在@ResponseBody(比如說json)中傳遞期望的數據,並且如果某個「usecase」強制你重定向do重定向。另外,作爲建議,不工作與事務性作用域在控制器的水平,但做它在服務層,而不是

@ResponseBody 
@RequestMapping(value = "/profile/edit/{id}", method = RequestMethod.POST) 
public String updateUser(@PathVariable("id") final Integer id, String firstname, String lastname, final RedirectAttributes redirectAttributes, HttpServletResponse response) { 

    respository.updateFirstname(id,firstname); 
    respository.updateLastname(id, lastname); 

    if(someCondition == "redirectMe"){ 
     redirectAttributes.addFlashAttribute("message", "Successfully changed.."); 
     response.sendRedirect("/profile"); 
    } 

return "some_data_for_view"; 
} 
0
@GetMapping("/abc/def") 
public void some_method(HttpServletResponse response){ 
//to do 
response.sendRedirect("url"); 
}