我从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
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打印显示:
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (profile/profilePage:16)
根据书,一切都应该没问题,但是我仍然遇到错误,为什么?
最佳答案
我认为您需要:
将“ profileForm
”添加到模型。
将“ @ModelAttribute("profileForm")
”添加到后控制器。
另外,您可以简化您的@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";
}
}