I am using spring framework 3.
I have a form for posting comments to the article. When the form is submitted, it is checked if there any errors.
In case there is no errors, controller returns string
"redirect:entryView/"+comment.getEntryId();
And everything is okay.
But when there are some errors, if controller returns
"redirect:entryView/"+comment.getEntryId();
The errors should be displaed near the form with spring-form.tld tags:
<form:errors path="author"/>
But there are no displayed errors!
When i am trying to return
"entryView/"+comment.getEntryId();
Without redirect: prefix, then it is going to /rus/WEB-INF/jsp/entryView/8.jsp and there is HTTP Status 404. But it must go to http://example.com/rus/entryView/8, i.e page where the article and form for comments are!
This is view resolver:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
What should i do?
Rest of controller:
@Controller
public class CommentController {
private RusService rusService;
private CommentValidator commentValidator;
@Autowired
public CommentController(RusService rusService,CommentValidator commentValidator){
this.rusService = rusService;
this.commentValidator = commentValidator;
}
@RequestMapping(value="/addComment",method=RequestMethod.POST)
public String addComment(Comment comment,BindingResult result){
commentValidator.validate(comment, result);
if(result.hasErrors()){
return "redirect:entryView/"+comment.getEntryId();
}else{
rusService.postComment(comment);
return "redirect:entryView/"+comment.getEntryId();
}
}
}
The display of errors in
<form:errors path="author"/>works like this:Errorsare saved as an attribute in theHttpServletResponseobjectresponse.getAttribute(name)to find theErrorsinstance to displayWhen you use
redirect:url, you are instructing Spring to send a302 Foundto the client’s browser to force the browser to make a second request, to the new URL.Since the redirected-to page is operating with a different set of request/response objects, the original
Errorsis lost.The simplest way to pass “errors” to a page you want to redirect to in order for the new page to display it would be to handle it yourself, by adding a message to the
Sessionobject which the second page’s controller can look at (or by passing an argument in the URL).