我试图在我的spring应用程序中使用thymeleaf处理表单提交,我集成了
这个例子在我的应用程序上运行得很好。我正在尝试改变它,但这是我作为一个异常所得到的
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'recruiter' cannot be found on null
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213) ~[spring-expression-5.2.3.RELEASE.jar:5.2.3.RELEASE]
...这就是我试图用thymeleaf处理的对象
public class FormRec {
private String recruiter;
public String getRecruiter() {
return recruiter;
}
public void setRecruiter(String recruiter) {
this.recruiter = recruiter;
}
}这是我的Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.service.minimicroservice.objects.FormRec;
@Controller
public class MyController {
@GetMapping("/form")
public String greetingForm(Model model) {
model.addAttribute("recForm", new FormRec());
return "form";
}
@PostMapping("/form")
public String greetingSubmit(@ModelAttribute FormRec rec) {
return "result";
}
}result.html
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'Recruiter: ' + ${rec.recruiter}" />
<a href="/form">Submit another message</a>
</body>
</html>form.html的一部分
<body>
<form action="#" th:action="@{/form}" th:object="${recForm}" method="post">
<div class="form-row m-b-55">
<div class="name">Recruiter<br> Name</div>
<div class="value">
<div class="row row-space">
<div class="col-2">
<div class="input-group-desc">
<input class="input--style-5" type="text" name="first_name" th:field="*{recruiter}">
<label class="label--desc">Full Name</label>
</div>
</div>
...为了引用FormRec对象,我在form.html中使用recForm作为th:object,在result.html中使用rec来引用它。
注意:在提交表单时,我向th:field="*{recruiter}"输入文本传递一个值(不是空)。
发布于 2020-01-23 20:14:13
您必须为数据绑定到的ModelAttribute rec命名。因此,在控制器方法中这样做(请注意name = "rec"):
public String greetingSubmit(@ModelAttribute(name = "rec") FormRec rec) {
...
}应该管用的。
附加解释:
我仔细研究了为什么会出现这种情况,这是因为Spring的ModelAttribute注释默认情况下是从类型的名称而不是参数的名称推断出来的(您提供的示例链接说它是方法参数名,但它似乎是错误的)。
因此,在本例中,Spring将formRec (注意camelCase,它在类名被称为FormRec时所期望的)发送给result.html,而不是您所期望的rec。
如果我的解释不太合理,那么这就是关于ModelAttribute的Spring文档
默认模型属性名是根据非限定类名从声明的属性类型(即方法参数类型或方法返回类型)推断出来的:例如,"orderAddress“表示类"mypackage.OrderAddress","orderAddressList”表示“列表”。
https://stackoverflow.com/questions/59886049
复制相似问题