“${#fields.hasErrors('*')}” always false - Redirect Problem

寵の児 提交于 2021-02-11 09:37:06

问题


My controller looks like this:

    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (!bindingResult.hasErrors()) {
          //No errors
          //No return
        }

        return "redirect:/event/{id}";               
    }

My @GetMapping is:

 @GetMapping("/event/{id}")
    public ModelAndView eventDetail(@PathVariable("id") long id) {

        ModelAndView model = new ModelAndView("event/details");
        Event event = eventoRepository.findById(id).get();
        model.addObject("event", evento);
        model.addObject("guests", event.getGuests());
        model.addObject("guest",new Guest());

        return model;

    }

I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

How return to this path /event/{id} without redirect?


回答1:


I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

Right. It looks like you always redirect. Because of that a method annotated with @GetMapping("/event/{id}") is called, the form most likely is reseted to fresh state and there are no more errors making expression always false.

How return to this path /event/{id} without redirect?

Simply return name of the view (template) containing the form. Most likely it's the same what's returned by method annotated with @GetMapping("/event/{id}").

You should follow an approach from this guide. Return without redirect if the form contains error, and redirect otherwise.

Edit: You should also provide additional objects to the model. Instead of populating model in each method (Get, Post etc.) you may extract common objects to a method annotated with @ModelAttribute. According to javadoc such a method can accept similar parameters as methods annotated with @RequestMapping.

For your case something like this should work fine:

    @ModelAttribute
    void supplyModel(@PathVariable("id") long id, Model model) {
        Event event = eventoRepository.findById(id).get();
        model.addAttribute("event", evento);
        model.addAttribute("guests", event.getGuests());
        model.addAttribute("guest",new Guest());
    }

    @GetMapping("/event/{id}")
    public String eventDetail(@PathVariable("id") long id) {
        return "event/details";

    }

    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (bindingResult.hasErrors()) {
            // Has errors
            return "event/details";
        }

        // No errors
        return "redirect:/event/" + id;
    }


来源:https://stackoverflow.com/questions/60290677/fields-haserrors-always-false-redirect-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!