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

标签 spring-mvc spring-boot thymeleaf

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

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

我读过几个答案,建议将 BindingResult 直接放在 Controller 方法中的模型属性后面,但这似乎没有解决问题。这是我所拥有的

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

Controller 方法

@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;
    }

}

最佳答案

好吧,按照我一贯的风格,我自己解决了。问题实际上出在获取映射而不是后映射中,例如。我需要

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

关于spring-mvc - Thymeleaf Spring MVC 表单 - 既不是 BindingResult 也不是 bean 名称的普通目标对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52163204/

相关文章:

java - Spring Tomcat和静态资源和mvc :resources

spring-boot 没有创建 hsqldb 数据库

html - 如何使用 Spring 和 Thymeleaf 显示没有 html 标签的消息

spring-mvc - 如何使用 Thymeleaf 标准表达式语法比较模型的两个变量?

java - 测试 Thymeleaf 表单/Spring MVC Controller 交互的最佳方法

java - 创建名称为 'clientsDaoImpl' : Injection of autowired dependencies failed; 的 bean 时出错

java - Spring MVC : issue between xml and annotation configurations

spring - AuthorizationServerConfigurerAdapter 已弃用

java - 如何从 Spring boot 依赖注入(inject)中的对象列表中查找特定的类对象

spring-boot - 在Spring Boot Gradle项目中手动添加第3方jar