代码之家  ›  专栏  ›  技术社区  ›  PDStat

thymeleaf spring mvc form-bean名称既不是bindingresult也不是plain目标对象

  •  1
  • PDStat  · 技术社区  · 6 年前

    我有一个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;
        }
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   karen    6 年前

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

    <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
        }
        ....
    
        2
  •  0
  •   PDStat    6 年前

    好吧,按照我通常的方式,我自己解决了。问题实际上是在GET映射中,而不是在POST映射中,例如我需要

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