简体   繁体   中英

Spring 3 annotation-based validation: password and confirm password

In my Spring 3 MVC application a users need to save a password and it would be a nice feature if they also were able to confirm the password upon saving.

In the bean I'm using annotation based validation. Is there an annotation validator available for performing this checking?

After some googleing I found this blog: http://gochev.blogspot.com/2010/06/spring-mvc-spring-bean-validation.html . But I guess I'm missing a jar-lib here as Eclipse is unable to find/suggest any jars. Anyone know what jar I need for this to work?

Thanks in advance :)

I wrote the following in order to validate passwords:

Constraint implementation:

 package com.test.web.validation.user;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PasswordsEqualConstraintValidator.class)
public @interface PasswordsEqualConstraint {
String message();

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

package com.test.web.validation.user;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.test.logic.dto.UserDto;

public class PasswordsEqualConstraintValidator implements
    ConstraintValidator<PasswordsEqualConstraint, Object> {

@Override
public void initialize(PasswordsEqualConstraint arg0) {
}

@Override
public boolean isValid(Object candidate, ConstraintValidatorContext arg1) {
    UserDto user = (UserDto) candidate;
    return user.getPassword().equals(user.getPasswordRepeat());
}
}

My DTO Object:

package com.test.logic.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import com.esldic.web.validation.user.EmailExistsConstraint;
import com.esldic.web.validation.user.PasswordsEqualConstraint;

@PasswordsEqualConstraint(message = "passwords are not equal")
public final class UserDto extends AbstractDto implements Serializable {

private static final long serialVersionUID = 1L;

private Long id;

@NotNull
@Size(min = 3, max = 30)
@EmailExistsConstraint(message = "email is not available")
private String email;

private String username;

@NotNull
@Size(min = 2, max = 30)
private String password;

@NotNull
@Size(min = 2, max = 30)
private String passwordRepeat;
...
}

Finally, my controller

package com.test.web.controllers;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.test.logic.dto.UserDto;

@Controller
public final class SignupController {

@Autowired
private Validator validator;

@RequestMapping(value = "/signup.html", method = RequestMethod.POST)
public @ResponseBody
ModelAndView handleSignupForm(@ModelAttribute UserDto candidate,
        HttpServletResponse response) throws ServiceException {
    Set<ConstraintViolation<UserDto>> failures = validator
            .validate(candidate);

    if (!failures.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return ValidationHelper.validationMessages(failures);

    } else {
        return userService.create(candidate);
    }
}

Also, in google you will find a lot of samples with JSR-303 bean validation.

You need the Hibernate Validation and JSR 303 Api jar.

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.1.0.Final</version>                        
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>

See this question: Cross field validation with Hibernate Validator (JSR 303)

there are several ways to deal with that problem.

Accepted solution given by Cyril Deba worked for me too. But then I had to make another annotation for ResetPassword and ChangePassword Page, as they have different DTO. To overcome that I changed isValid to below code. Although it could be acheived by implementing an interface too, but I think this one is more realistic. Hope it will help.

@Override
public boolean isValid(Object candidate, ConstraintValidatorContext context) {

    try {
        Method methodGetPassword = candidate.getClass().getMethod("getPassword");
        Method methodGetConfirmpassword = candidate.getClass().getMethod("getConfirmpassword");

        if(methodGetPassword.invoke(candidate) == null && methodGetConfirmpassword.invoke(candidate)==null) 
            return true;
        else if(methodGetPassword.invoke(candidate) == null )
            return false;
        return methodGetPassword.invoke(candidate).equals(methodGetConfirmpassword.invoke(candidate));

    } catch (NoSuchMethodException ex) {
        ex.printStackTrace();
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM