spring验证程序的目标无效

oug3syen  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(292)

我正在尝试验证字符串电子邮件,以检查它是否已出现在我的mysql数据库中,当我使用已使用的电子邮件执行时,会出现以下错误:
java.lang.illegalstateexception:验证程序[co2103.hw2.controller]的目标无效。testresultsvalidator@62b41c6]:org.springframework.validation.beanpropertybindingresult:1 errors字段“email”上的对象“testresults”中存在错误:拒绝值[@le.ac.uk]; 代码[email.testresults.email,email.email,email.java.lang.string,email];参数[];默认消息[已由其他用户提供!请使用另一个!]
这是验证码

public class TestResultsValidator implements Validator{
private TestResultsRepository TrRepo;
private HomeTestRepository HTRepo;
public TestResultsValidator (TestResultsRepository TrRepo, HomeTestRepository HTRepo) {
    this.TrRepo = TrRepo;
    this.HTRepo = HTRepo;
}
@Override
public boolean supports(Class<?> clazz) {
    return TestResults.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {

    TestResults tr = (TestResults) target;

    for(TestResults t : TrRepo.findAll()) {
        //SAME EMAIL
        if (tr.getEmail().equals(t.getEmail())) {
            errors.rejectValue("email", "email", "is already provided by a different user! Please user another one!");
        System.out.println("Email is already taken by a different user, please try another username");
        break;
        }

控制器代码

//Add new results
@RequestMapping(value = "/addResults",method = {RequestMethod.POST , RequestMethod.GET})
public String newHotel(@Valid @ModelAttribute TestResults results, BindingResult result, Model model) {
    if (result.hasErrors()) {
         model.addAttribute("errors", result);
        return "start";
    }
    else {
    trRepo.save(results);
    return "Submitted";
}}
nbewdwxp

nbewdwxp1#

您需要将验证程序注册到spring。
validtor的第一个ad组件注解。

@Component
public class TestResultsValidator implements Validator{
.....
}

在控制器中注册。

@Controller
class TestResultController {
    @Autowired
    TestResultsValidator testResultsValidator ;

    @InitBinder("testResultsValidator")
    protected void initMessageBinder(WebDataBinder binder) {
        binder.addValidators(testResultsValidator );
    }
}

相关问题