gpt4 book ai didi

java - spring boot 自定义 validator 运行两次

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:43:53 25 4
gpt4 key购买 nike

我有一个带有我创建的自定义 validator 的 spring boot 应用程序,与此处描述的非常相似:

How to disable Hibernate validation in a Spring Boot project

我已经尝试了建议的解决方案,这意味着我将以下行添加到 application.properties 文件中:

spring.jpa.properties.javax.persistence.validation.mode=none

这是代码(部分):

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = ReCaptchaResponseValidator.class)
public @interface ReCaptchaResponse {
String message() default "RECAPTCHA_RESPONSE_INVALID";

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

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

然后我有:

import org.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;


public class ReCaptchaResponseValidator implements
ConstraintValidator<ReCaptchaResponse, String> {
private boolean status = true;

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
final String secretKey = "xxxxxxxxxx";

System.out.println("Calling isValid with value: " + value);


try {
String url = "https://www.google.com/recaptcha/api/siteverify?"
+ "secret=" + secretKey
+ "&response=" + value;

InputStream res = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));

StringBuilder sb = new StringBuilder();

int cp;

while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}

String jsonText = sb.toString();

res.close();

JSONObject json = new JSONObject(jsonText);

return json.getBoolean("success");
} catch (Exception e) {
}

return false;
}

然后我有:

public class MyModel {
@ReCaptchaResponse
private Srting recaptcha;
}

然后我停止并重新编译项目,但 validator 仍然运行了两次。我不知道为什么会这样,我使用的是最新的 spring boot 版本,而建议的解决方案是从 2014 年开始的……也许从那以后发生了一些变化?有什么想法吗?

谢谢。

最佳答案

我不知道为什么,但是在我的 Controller 中将 @Valid @RequestBody 替换为 @Validated @RequestBody 后,它似乎可以解决问题,现在 validator 运行了只有一次。

关于java - spring boot 自定义 validator 运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56957799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com