Spring验证器 - 客户端发送的请求在语法上是不正确的

时间:2015-03-20 18:21:25

标签: spring hibernate validation

我的朋友帮我设置了我的第一个spring / hibernate项目,现在我正在尝试实现一个自定义验证器。我已经有一个使用anotations进行验证的RegistrationForm模型。但是,现在我需要实现一个密码验证器 - 检查密码和confirmPassword是否相等。

问题:当我发布POST时,如果密码匹配,则保存数据。如果它们不匹配,那么在跟随行的验证器中,我从标题中得到错误。

errors.rejectValue("confirmPassword", "valid.passwordConfDiff");

客户端发送的请求在语法上是不正确的。

我遵循的教程: http://examples.javacodegeeks.com/enterprise-java/spring/mvc/spring-mvc-password-example/

这就是我所拥有的:

控制器:

@Controller
@RequestMapping("/")
//@SessionAttributes(value = {"registerForm"})
@ComponentScan("ba.codecentric.movienight")
public class FrontController {

    @Autowired
    private UserService userService;

    @Autowired  
    @Qualifier("passwordValidator")
    private PasswordValidator validator;

    @InitBinder("password")
    private void initBinder(WebDataBinder binder) {
            binder.setValidator(validator);
        }

    @RequestMapping(method = RequestMethod.GET)
    public String initIndex(Model model){       
        model.addAttribute("registerForm", new RegisterForm());

        Password password = new Password();
        model.addAttribute("password", password);

        return "index";
    }

    @RequestMapping(value="/register", method=RequestMethod.POST)
    public String addNewUser(@Valid @ModelAttribute("registerForm") RegisterForm registerForm,
               BindingResult result, Model model, HttpServletRequest request, @Validated Password password){

        if(result.hasErrors()){
            model.addAttribute("error", true);
            model.addAttribute("userIsRegistering", "<script>$('#loginbox').hide(); $('#signupbox').show();</script>");
            System.out.println("ERROR");
            return "index";
        }

        User user = new User();

        user.setUserName(registerForm.getUserName());
        user.setPassword(registerForm.getPassword());       

        userService.addNewUser(user);

        return "index";
    }       
}

密码验证器:

     public class PasswordValidator implements Validator{


    public boolean supports(Class<?> paramClass) {
        return Password.class.equals(paramClass);   
    }

    public void validate(Object obj, Errors errors) {

        Password password = (Password) obj;

        if (!password.getPassword().equals(password.getConfirmPassword())) {
                errors.rejectValue("confirmPassword", "valid.passwordConfDiff");        
        }

    }
}

RegistrationForm:

public class RegisterForm {
            @NotBlank
            @NotEmpty 
            private String userName;
            @NotBlank
            @NotEmpty 
            @Size(min=7,max=16,message="Password range error")
            private String password;

            @NotBlank
            @NotEmpty
            private String confirmPassword;
        //getters setters
        }

注册表格jsp:

 <form:form id="signupform" class="form-horizontal" role="form" commandName="registerForm" action="${pageContext.request.contextPath}/register" method="post">

                            <form:errors path="*" cssClass="errorblock" element="div" class="alert alert-danger" role="alert"  />

                            <div class="form-group">
                                <label for="userName" class="col-md-3 control-label">User Name</label>
                                <div class="col-md-9">
                                    <form:input type="text" path="userName" class="form-control" name="userName" placeholder="User Name" />
                                </div>
                            </div>

                            <form:errors path="userName" element="div" class="alert alert-danger" role="alert" />

                            <div class="form-group">                            
                                <label for="password" class="col-md-3 control-label">Password</label>
                                <div class="col-md-9">
                                    <form:password path="password" class="form-control" name="password" placeholder="Password"/>
                                </div>
                            </div>

                            <form:errors path="password" element="div" class="alert alert-danger" role="alert" />

                            <div class="form-group">
                                <label for="confirmPassword" class="col-md-3 control-label">Confirm Password</label>
                                <div class="col-md-9">
                                    <form:password path="confirmPassword" class="form-control" name="confirmPassword" placeholder="Confirm Password"/>
                                </div>
                            </div>                                                                

                            <form:errors path="confirmPassword" class="alert alert-danger" role="alert" />

                            <div class="form-group">
                                <!-- Button -->                                        
                                <div class="col-md-offset-3 col-md-9">
                                    <form:button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i> &nbsp Sign Up</form:button>                                        
                                </div>
                            </div>                                                                           

                        </form:form>

1 个答案:

答案 0 :(得分:1)

我也面临同样的问题。

@RequestMapping(method = RequestMethod.POST)
public String processForm(
        @Valid @ModelAttribute("student") Student student, Model model,
        BindingResult result) {
    if (result.hasErrors()) {
        return "registration";
    }
    return "success";
}

当对象学生具有无效属性时,此代码会给出错误:客户端发送的请求在语法上不正确。

但是,如果更改了参数student和model的顺序,则此方法按预期工作。 如,

public String processForm(Model model, @Valid @ModelAttribute("student") Student student, BindingResult result)

public String processForm( @Valid @ModelAttribute("student") Student student, BindingResult result, Model model) 两者都按预期工作。

请让我知道这背后的科学是什么。