2
顯示在JSP驗證消息我有這樣形式如何在彈簧MVC使用重定向
<form:form method="POST" action="posts/add" modelAttribute="post">
<table>
<tr>
<td><form:label path="author"><spring:message code="blog.posts.author.name"/></form:label></td>
<td>
<form:select path="author">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${authors}" />
</form:select>
</td>
<td><form:errors path="author" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="text"><spring:message code="blog.posts.text"/></form:label></td>
<td><form:textarea path="text" rows="5" cols="30"/></td>
<td><form:errors path="text" cssClass="error" /></td>
</tr>
</table>
<input type="submit" value="<spring:message code="blog.posts.save"/>" />
</form:form>
併爲它
@Controller
public class PostsController {
@Autowired
private PostDAO postDao;
@Autowired
private Validator validator;
@RequestMapping("/posts")
public String showAllPosts(ModelMap model) {
List<String> authors = new ArrayList<String>();
authors.add("John B.");
authors.add("Jack C.");
List<Post> posts = postDao.findAll();
model.addAttribute("posts", posts);
model.addAttribute("authors", authors);
return "posts";
}
@ModelAttribute("post")
public Post getPost(ModelMap model) {
return new Post();
}
@RequestMapping(value = "/posts/add", method = RequestMethod.POST)
public String savePost(@ModelAttribute("post") Post post, BindingResult errors, ModelMap model) {
validator.validate(post, errors);
if (errors.hasErrors()) {
model.addAttribute("posts", postDao.findAll());
return "posts";
}
postDao.addPost(post);
model.addAttribute("posts", postDao.findAll());
return "redirect:/posts";
}
我使用自定義的驗證控制器。
它顯示在
if (errors.hasErrors()) {
model.addAttribute("posts", postDao.findAll());
return "posts";
}
我試着使用redirect:/posts
在return語句
但在這種情況下,它並不頁面上顯示錯誤消息的情況下,錯誤信息頁面。
另外?我試圖添加到控制器。但沒有成功。
@SessionAttributes("post")
是否有任何方式重定向到頁面並在其上顯示錯誤消息?
我使用彈簧3.0.5。無論如何,我不清楚明白我應該添加什麼屬性 –
@ConstantineGladky讓我們舉個例子吧。客戶端發送'POST'請求到'/ posts/add'。您添加模型和請求屬性,然後將重定向發送到'/ posts'。這將導致服務器發送302到客戶端。客戶端將收到這個302,並向'/ posts'發送一個新的GET請求。該新請求具有與您之前添加的請求屬性完全無關的一組單獨的請求屬性。 –
是的。這不會造成任何誤解。但我試圖找出如何實現它(傳輸錯誤)。我應該添加到redirectAttributes,以及我應該在哪裏使用它?據我瞭解,我應該添加一個處理/帖子的方法,並添加到我保存在redirectAttributes中的模型? –