我重写了 Mastering Spring 书中的代码,但它不起作用,因为我一直遇到异常:
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'profileForm' available as request attribute
我的表格:
<form th:action="@{/profile}" th:object="${profileForm}" method="post" class="col m8 s12 offset-m2">
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.twitterHandle}" id="twitterHandle" type="text"/>
<label for="twitterHandle" th:text="#{twitter.handle}">Identyfikator Twitter</label>
</div>
<div class="input-field col s6">
<input th:field="${profileForm.email}" id="email" type="email"/>
<label for="email">Adres e-mail</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.birthDate}" id="birthDate" type="text"/>
<label for="birthDate" th:text="#{birthdate}">Data urodzenia</label>
</div>
</div>
<div class="row s12 center">
<button class="btn indigo waves-effect waves-light" type="submit" name="save">Wyślij
<i class="mdi-content-send right"></i>
</button>
</div>
</form>
我的POJO:
package masterspringmvc.profile;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ProfileForm {
private String twitterHandle;
private String email;
private LocalDate birthDate;
private List<String> tastes = new ArrayList<>();
// getters setters
}
我的 Controller :
@Controller
public class ProfileController {
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String displayProfile() {
return "profile/profilePage";
}
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public String saveProfile(ProfileForm profileForm) {
System.out.println("Profil: " + profileForm);
return "redirect:/profile";
}
}
Tomcat 打印显示:
处理器“org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor”执行期间出错(profile/profilePage:16)
根据书,一切都应该没问题,但我仍然收到错误,为什么?
最佳答案
我认为你需要:
- 将“
profileForm
”添加到模型中。 - 将“
@ModelAttribute("profileForm")
”添加到帖子 Controller 。
此外,您还可以简化您的@RequestMapping
@Controller
public class ProfileController {
@GetMapping("/profile")
public String displayProfile(Map<String, Object> model) {
model.put("profileForm", new ProfileForm());
return "profile/profilePage";
}
@PostMapping("/profile")
public String saveProfile(@ModelAttribute("profileForm") ProfileForm profileForm) {
System.out.println("Profil: " + profileForm);
return "redirect:/profile";
}
}
关于java - 使用 Thymeleaf 的表单不适用于 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46104319/