【发布时间】:2016-06-02 14:01:12
【问题描述】:
我遇到了一个奇怪的错误,表单数据在提交时绑定到一个完全错误的对象。
我正在使用带有百里香的 spring 并具有以下形式:
<form method="post" th:action="@{/backend/user/create}"
th:object="${userInCreation}" id="userCreateForm">
<input th:field="*{firstName}" />Create user</button>
</form>
我要绑定的对象是
public class UserInCreation implements Serializable {
private String firstName;
public UserInCreation() {}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
绑定发生在控制器中
@Controller
@RequestMapping("/backend/user")
public class UserController {
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createUserForm(UserInCreation userInCreation) {
return "backend/user/create";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createUser(@Valid UserInCreation userInCreation, BindingResult result, Model model) {
return "backend/user/index";
}
}
这很好用,尽管有一个大问题:我在 firstName 字段中输入的数据也绑定到 Spring-Security Principal,我将其作为 ModelAttribute 提供:
@ModelAttribute("currentAuthor")
public User getCurrentAuthor(Principal principal, HttpSession session) {
User author = (User) ((Authentication) principal).getPrincipal();
return author;
}
User 类也有一个字段 firstName,这已更改。所以当我在表单中输入“Some name”并提交时,突然间,校长的名字将是“Some name”。有什么想法吗?
【问题讨论】:
标签: java spring spring-mvc data-binding