2

我有一个这样的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){

    }
}

当用户提交表单时,它会来到帖子,然后验证输入并保存它。如何向视图发送成功消息和错误消息。现有实施中是否需要进行任何更改?

4

2 回答 2

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 验证文档的第 6.7 节

于 2012-04-10T16:22:03.467 回答
1

您可以保存在请求中:model.addAttribute("message","sussess");

于 2012-04-10T14:31:41.257 回答