我有一个jsp页面,如下所示:
<form:form action="userRegistration" name="userRegistrationForm" commandName="userRegistration">
<form:input path="userName"/>
<form:input path="houseNo"/>
</form:form>
以及所有必填字段。
在控制器中我使用如下:
@RequestMapping(method=RequestMethod.GET)
public String registration(ModelMap model,HttpSession session) {
UserRegistration userRegistration = service.createUserRegistration();
model.addAttribute("userRegistration",userRegistration);
return "registrationview";
}
@RequestMapping(method=RequestMethod.POST)
public String getRegistration(UserRegistration userRegistration, HttpSession session, ModelMap model) {
boolean result = validateAndSaveData(userRegistration);
if (result){
}
}
当用户提交表单时,它会到达帖子然后验证输入并保存。 如何向视图发送成功消息和错误消息。现有实施中是否需要进行任何更改?
答案 0 :(得分:4)
@RequestMapping(method=RequestMethod.POST)
public String getRegistration(UserRegistration userRegistration, HttpSession session, ModelMap model) {
boolean result = validateAndSaveData(userRegistration);
if (result){
model.addAttribute("successMsg", "Form successfully submitted");
return "successPage";
}
else {
model.addAttribute("errorMsg", "Your form submission contains errors.");
return "formPage";
}
}
我同意Shagaan的看法,你应该考虑使用Spring对JSR-303验证的内置支持来验证表单。这里有一些关于如何做到这一点的信息。首先,使用JSR-303(javax.validation)注释注释您的表单:
public class UserRegistration {
@NotNull
@Size(max=7)
private String name;
@Min(0)
private int houseNo;
...
}
然后使用“@Valid”在控制器方法中注释您的模型:
@RequestMapping(method=RequestMethod.POST)
public String getRegistration(@Valid UserRegistration userRegistration, BindingResult result, HttpSession session, ModelMap model) {
if (result.hasErrors()){
model.addAttribute("errorMsg", "Your form submission contains errors.");
return "formPage";
}
model.addAttribute("successMsg", "Form successfully submitted");
return "successPage";
}
Spring的BindingResult会自动将错误绑定到您的表单对象,因此在您的jsp中,您可以这样做:
<form:form action="userRegistration" name="userRegistrationForm" commandName="userRegistration">
<form:input path="userName"/> <form:errors path="userName" cssClass="error"/>
<form:input path="houseNo"/> <form:errors path="houseNo" cssClass="error"/>
</form:form>
要使用Spring验证,您需要在类路径中使用Validation-api(JSR-303规范)和实现(Hibernate-Validator)。见Spring validation docs
的第6.7节答案 1 :(得分:1)
您可以在请求中保存:model.addAttribute(&#34; message&#34;,&#34; sussess&#34;);