【问题标题】:Thymeleaf Spring MVC form - Neither BindingResult nor plain target object for bean nameThymeleaf Spring MVC 表单 - Bean 名称的 BindingResult 和普通目标对象都不是
【发布时间】:2018-09-04 09:33:48
【问题描述】:

我有一个 thymeleaf 表单,它在提交后抛出以下异常

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute

我已经阅读了几个答案,建议将BindingResult 直接放在控制器方法中的模型属性之后,但这似乎并没有解决它。这就是我所拥有的

<form action="#" th:action="@{/capturedetails}" th:object="${command}" method="post">
  <div class="form-group" th:if="${mobilePhone} == null">
    <label for="mobilePhone">Mobile Phone</label> <input
      type="tel" class="form-control"
      id="mobilePhone"
      placeholder="Mobile Phone no." th:field="*{mobilePhone}"></input>
  </div>
  <div class="form-group" th:if="${secondEmail} == null">
    <label for="secondEmail">Secondary Email</label>
    <input type="email" class="form-control"
      id="secondEmail" placeholder="Secondary Email" th:field="*{secondEmail}"></input>
  </div>
  <button type="submit">Submit</button>
</form>

控制器方法

@PostMapping(value = "/capturedetails")
public String updateProfile(@ModelAttribute("command") CaptureDetailsFormCommand command, BindingResult bindingResult, Model model) {
    model.addAttribute("command", command);
    return "redirect: someWhere";
}

还有命令对象

public class CaptureDetailsFormCommand {

    private String mobilePhone;

    private String secondEmail;

    public String getMobilePhone() {
        return mobilePhone;
    }

    public void setMobilePhone(String mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public String getSecondEmail() {
        return secondEmail;
    }

    public void setSecondEmail(String secondEmail) {
        this.secondEmail = secondEmail;
    }

}

【问题讨论】:

    标签: spring-mvc spring-boot thymeleaf


    【解决方案1】:

    按照我通常的风格,我自己解决了。问题实际上出在 Get Mapping 而不是 post 映射中,例如。我需要

    @GetMapping(value = "/capturedetails")
    public ModelAndView captureDetails() {
        ModelAndView mav = new ModelAndView("capturedetails");
        mav.addObject("command", new CaptureDetailsFormCommand());
        return mav;
    }
    

    【讨论】:

      【解决方案2】:

      将模型属性的名称添加到您的表单中,如下所示:

      <form action="#" modelAttribute="command" ...
      

      并检查 bindingResult 没有像这样的错误:

      @PostMapping(value = "/capturedetails")
      public String updateProfile(@ModelAttribute("command") CaptureDetailsFormCommand command, BindingResult bindingResult, Model model) {
      
          if (bindingResult.hasErrors()) {
             return "error"; //This should return some kind of error
          }
          ....
      

      【讨论】:

      • 这相当于我设置的百里香中的th:object="${command}"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2013-05-23
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多