gpt4 book ai didi

java - Thymeleaf Bean 名称 'person' 的 BindingResult 和普通目标对象均不可用作请求属性

转载 作者:行者123 更新时间:2023-12-04 02:36:30 24 4
gpt4 key购买 nike

据我所知,这是正确设置的,但出现以下错误:

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

形式
<form action="#" th:action="@{/person}" th:object="${person}" method="post" th:required="required">
<input type="text" th:field="*{subject}" class="contact col-md-6" placeholder="Name *" th:required="required"/>
<input type="text" th:field="*{name}" class="contact col-md-6" placeholder="Name *" th:required="required"/>
<input type="text" th:field="*{lastName}" class="contact col-md-6" placeholder="Name *" th:required="required"/>
<input type="email" th:field="*{email}" class="contact noMarr col-md-6" placeholder="E-mail address *" th:required="required"/>
<textarea name="comment" class="contact col-md-12" th:field="*{message}" placeholder="Message *"></textarea>
<input type="submit" id="submit" class="contact submit" value="Send message"/>
</form>

人.java
public class Person {

private int id;
private String name;
private String lastName;
private String email;
private String subject;
private String message;

....
}

Controller
@Controller
public class ApplicationController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public String indexPage() {
return "index";
}

@RequestMapping(value="/person", method=RequestMethod.GET)
public String contactForm(Model model) {
model.addAttribute("person", new Person());
return "index";
}

@RequestMapping(value="/person", method=RequestMethod.POST)
public String contactSubmit(@ModelAttribute Person person, Model model) {
model.addAttribute("person", person);
return "result";
}
}

我看了 Spring-boot and Thmeleaf setup看起来我的设置是相同的。

--------------------- 更新 1 -----------------------

我已将我的 post 方法更改为包含 BindingResult,但没有成功。
@RequestMapping(value="/person", method=RequestMethod.POST)
public String contactSubmit(@Valid @ModelAttribute Person person, BindingResult bindingResult, Model model) {

if(bindingResult.hasErrors()){
System.out.println("There was a error "+bindingResult);
System.out.println("Person is: "+ person.getEmail());
return "index";
}

model.addAttribute("person", person);
return "result";
}

最佳答案

您忘记添加 BindingResult 您的 @ModelAttribute :

@RequestMapping(value="/person", method=RequestMethod.POST)
public String contactSubmit(@ModelAttribute Person person, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
//errors processing
}
model.addAttribute("person", person);
return "result";
}

我已经回答过这样的问题:
  • html form validation using thymeleaf not working spring boot
  • 关于java - Thymeleaf Bean 名称 'person' 的 BindingResult 和普通目标对象均不可用作请求属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726525/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com