Answer the question
In order to leave comments, you need to log in
Hello. How to redirect from 1 controller to another if you need to insert an attribute on the page in 1 controller and then redirect?
Here is my code, it just redirects but does not throw an error. I need it to display an error on the page after the redirect in case of a validation error. Please tell me, I will be very grateful.
@RequestMapping(value = "/user/addComment", method = RequestMethod.POST)
public String addComment(HttpServletRequest req,@ModelAttribute("Comment")@Valid Comment comment, BindingResult bindingResult) throws IOException {
if (bindingResult.hasErrors()){
return "redirect:/user/detailedNews";
}
Long idNews= Long.parseLong(req.getParameter("idNews"));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
AppUserPrincipal user =(AppUserPrincipal)auth.getPrincipal();
commentService.saveComment(idNews,user.getUser(),comment);
return "redirect:/user/detailedNews";
}
Answer the question
In order to leave comments, you need to log in
On errors, no redirects are made, on an error, the template name must be returned:
if (bindingResult.hasErrors()) {
return "detailed_news_template";
}
@RequestMapping(value = "/user/addComment", method = RequestMethod.POST)
public String addComment(HttpServletRequest req, @ModelAttribute("Comment") @Valid Comment comment, BindingResult bindingResult, RedirectAttributes redirectAttributes) throws IOException {
if (bindingResult.hasErrors()) {
redirectAttributes.addFlashAttribute("errors", bindingResult.getAllErrors());
return "redirect:/user/detailedNews";
}
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question