【问题标题】:Spring binds form data to multiple (wrong) objectsSpring 将表单数据绑定到多个(错误的)对象
【发布时间】: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


    【解决方案1】:

    我发现了问题所在。实际上,我有一个类型的函数

    @ModelAttribute("foo")
    public Foo xyz(@ModelAttribute("bar") Bar bar) {
      ...
    }
    

    这违反了规范,但起初它似乎有效。但它似乎也完全搞乱了数据绑定系统。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多