2

This is my Update User Method:

@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"; } 

All worked fine. Also the update in the Database. But the redirect is just a String and do not change the Path. Can someone tell me why?

1
  • 2
    Remove @ResponseBody. Also it is a terrible idea to make your controller transactional... You should have a service which is transactional boundary (so that you can reuse that stuff). Commented Nov 16, 2016 at 11:39

3 Answers 3

4

The problem is in the @ResponseBody annotation. Once it is removed, the redirection should work as expected. By using it, you override the default behavior of Spring MVC and returned value is treated as a raw response.

Sign up to request clarification or add additional context in comments.

Comments

3

It is still possible with @ResponseBody to do the redirect.

You could do it in following way which makes it possible that you still can pass the expected data in @ResponseBody (say json) and if some "usecase" forced you to do redirect. Also as suggested, do not work with Transactional scopes at controller level but do it on service layer instead

@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"; } 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.