<form action="" method="POST" id="newThreadForm">
<input type="text" placeholder="Title" id="title"/>
<input type="text" placeholder="Author" id="author"/>
<input type="text" placeholder="E-mail" id="email">
<!-- other fields... -->
</form>
有一个简单的课程:
public class Post {
private int id;
private String author;
private String email;
private String title;
//other fields
//getters and setters
}
如何在Controller方法中将用户在表单中键入的数据转换为Post对象?
@RequestMapping(value="path/to/", method=RequestMethod.POST)
public String newThread(Model model) {
//what should be there?
return "view-name";
}
我是否需要创建一个新类,如public class NewThreadForm
?将BindingResult参数添加到方法中?或者我该怎么办?谢谢你的回答。
UPD:我写道:
@RequestMapping(value="/{board}/new", method=RequestMethod.POST)
public String newThread(Model model, @PathVariable("board") String boardName, Post post, HttpServletRequest request) {
log.info("newThread()");
Board board = new Board();
board.setName(boardName);
post.setBoard(board);
post.setDeletePassword(DigestUtils.md5DigestAsHex(post.getDeletePassword().getBytes()));
post.setIp(request.getRemoteAddr());
Thread newThread = new Thread();
newThread.setOpPost(post);
threadDao.addThread(newThread);
return "redirect:/" + boardName;
}
但是当我发送表单数据时,Spring向我显示400错误:客户端发送的请求在语法上是不正确的。第一行log.info("newThread()");
没有运行。怎么了?
UPD2:这是&#34; id&#34;的原因,而不是#34; name&#34;表格html中的属性
答案 0 :(得分:1)
public String newThread(Post post, Model model) { ... }
应该有效。您将在方法中获得一个填充的Post
实例,您可以验证,保留等等。