Thymeleaf Spring MVC表单 - 既不是BindingResult也不是bean名称的普通目标对象

问题描述 投票:1回答:2

我有一个百里香形式,在提交后会抛出以下异常

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
2个回答
1
投票

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

<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
    }
    ....

0
投票

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

@GetMapping(value = "/capturedetails")
public ModelAndView captureDetails() {
    ModelAndView mav = new ModelAndView("capturedetails");
    mav.addObject("command", new CaptureDetailsFormCommand());
    return mav;
}
© www.soinside.com 2019 - 2024. All rights reserved.