2016-11-16 94 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"); 
}