[英]Adding two objects that belong to two different models with similar attribute names in one form using Thymeleaf and Spring MVC
[英]Two models in the form Spring MVC
假设我有一个用户模型:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="user_profile_id")
private UserProfile profile;
UserProfile模型:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="email")
private String email;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
我可以在控制器中添加此模型:
@RequestMapping(value = {"/user/{id}"}, method = RequestMethod.GET)
public String showUser(ModelMap model, @PathVariable int id) {
User user = userService.findById(id);
model.addAttribute("user", user);
return "UserView";
}
然后,可以像这样在.jsp页面中访问模型:
<form:form method="POST" modelAttribute="user">
<form:input type="text" path="username"/>
<form:input type="password" path="password"/>
</form>
但是问题是 -在编辑从控制器传递到.jsp页面的用户模型时,如何同时编辑位于User模型中的UserProfile模型?
这个问题不是重复的,因为我想知道“路径”是否可以处理层次结构属性,而不是如何仅将一个对象传递给视图。
这样使用
<form:input type="text" path="profile.email"/>
我不建议您将您的实体传递到前面,而是使用DTO进行解耦
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.