这个问题在这里已有答案:
我正在研究Spring MVC项目spring无法转换我的Post对象所需的用户对象。
我的NewPost对象:
public class NewPost {
private int postId;
@NotEmpty(message ="Title must not be empty!")
@Length(max = 50, message="Title must be less then 50 character")
private String title;
@NotEmpty(message ="Comment must not be empty!")
private String content;
@Length(max = 100, message="must be less then 100 character")
private String imagePath;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime publishDate;
private User user;
我的控制器:
//Get lates post from DB.
@RequestMapping(value = "/displayBlogPage", method = RequestMethod.GET)
public String displayLatesPost(Model model) {
List<NewPost> displayAllPost = new ArrayList<>();
displayAllPost = NPDao.getAllPost();
model.addAttribute("displayAllPost", displayAllPost);
//get newPost to the model.
model.addAttribute("newPost", new NewPost());
//get user object to the model
model.addAttribute("user", userDao.getUserbyId(1));
LocalDateTime timeStamp = LocalDateTime.now();
model.addAttribute("timeStamp", timeStamp);
return "NewPostPage";
}
//for add Post form
@RequestMapping(value = "/newPost", method = RequestMethod.POST)
public String createPost( @Valid @ModelAttribute("newPost") NewPost newPost, BindingResult result) {
if(result.hasErrors()){
return "NewPostPage";
}
NPDao.addNewPost(newPost);
return "redirect:NewPostPage";
}
我的JSP
<sf:form class="form-horizontal"
role="form" method="POST"
action="newPost" modelAttribute="newPost" >
<div class="col-md-12">
<div class="form-group">
<div class="col-md-6">
<sf:input type="text" class="form-control" path="title" placeholder="title" />
<sf:errors path="title" cssclass="error" ></sf:errors>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<sf:input type="text" class="form-control" path="imagePath" placeholder="image" />
<sf:errors path="imagePath" cssclass="error" ></sf:errors>
<sf:input type="text" class="form-control" path="publishDate" placeholder="date" value="${timeStamp}" />
<sf:errors type="date" path="publishDate" cssclass="error" ></sf:errors>
<sf:input type="text" class="form-control" path="user" placeholder="user" value="${user}"/>
<sf:errors path="user" cssclass="error" ></sf:errors>
<sf:input type="text" class="form-control" path="postId" placeholder="postid"/>
<sf:errors path="postId" cssclass="error" ></sf:errors>
<div class="form-group">
<div class="col-md-12">
<textarea type="text" class="form-control comment" name="comment" placeholder="Comment" required ></textarea>
<input type="submit" id="add"class="btn btn-default" value="Submit Post"/>
</div>
</div>
</div>
</sf:form>
这是例外:
无法将类型为java.lang.String的属性值转换为属性用户所需的类型com.sg.sophacms.Model.User;嵌套异常是java.lang.IllegalStateException:无法将类型为java.lang.String的值转换为属性用户所需的类型com.sg.sophacms.Model.User:找不到匹配的编辑器或转换策略