0
我有JSP,顯示在博客所有文章如何處理在Spring MVC的表單數據
<body>
<table>
<c:forEach var="post" items="${posts}">
<tr>
<td>${post.id}</td>
<td>${post.text}</td>
<td><a href="authors?name=${post.author}">Show author</a></td>
</tr>
</c:forEach>
</table>
<div>
<a href="posts/get.json">JSON</a> <a href="posts/get.xml">XML</a>
</div>
</body>
我控制器來處理它
@Controller
public class PostsController {
@Autowired
private PostDAO postDao;
@RequestMapping("/posts")
public String showAllPosts(ModelMap model) {
List<Post> posts = postDao.findAll();
model.addAttribute("posts", posts);
return "posts";
}
@RequestMapping("/posts/get")
public List<Post> getAllPosts() {
List<Post> posts = postDao.findAll();
return posts;
}
}
現在,我想補充的形式保存新帖子。
我想補充的形式在我的jsp
<form:form method="POST" action="/posts/add" modelAttribute="post">
<table>
<tr>
<td><form:label path="id">Id:</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="text">Text:</form:label></td>
<td><form:input path="text" /></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
我也加入到控制器。
@RequestMapping(value = "/posts/add", method = RequestMethod.POST)
public String saveAdd(@ModelAttribute("post") Post post, ModelMap model) {
model.addAttribute("posts", postDao.addPost(post));
return "posts";
}
領域模型Post.java
public class Post {
private int id;
private String author;
private String text;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
,但我得到
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'post' available as request attribute
你得到這個時候,當你的請求頁面或當您發佈到控制器? –
當請求頁/帖子 –
你能告訴我們你的Post.java嗎? – Dropout