D
D
Dmitry Pashko2018-02-26 21:34:35
Java
Dmitry Pashko, 2018-02-26 21:34:35

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

1 answer(s)
S
Sergey Gornostaev, 2018-02-26
@demonewe

On errors, no redirects are made, on an error, the template name must be returned:

if (bindingResult.hasErrors()) {
    return "detailed_news_template";
}

If you still need to pass data when redirecting, then you need to use RedirectAttributes :
@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 question

Ask a Question

731 491 924 answers to any question