gpt4 book ai didi

java - 如何在 Spring 4 MVC 中使用 javax.validation 和 JSON 请求?

转载 作者:行者123 更新时间:2023-11-30 08:16:28 26 4
gpt4 key购买 nike

我正在使用 Spring 4 MVC 开发 Web 应用程序。我想知道我是否可以使用 javax.validation API 验证 JSON 请求对象。例如,我有这段 entity 代码:

    ...       
@JsonProperty("cheFecha")
@NotNull
@Column(name = "che_fecha")
@Temporal(TemporalType.DATE)
@DateTimeFormat(style = "M-")
private Date SsiCheque.cheFecha;

@JsonProperty("cheMonto")
@NotNull
@JsonSerialize(using = CurrencySerializer.class)
@Column(name = "che_monto", precision = 10, scale = 2)
private BigDecimal SsiCheque.cheMonto;
...

我有 Controller 代码:

@RequestMapping(value = "/addCheck", method = RequestMethod.POST)
public @ResponseBody SsiCheque addChecks(@Valid SsiCheque ssiCheque, BindingResult result) {

//ssiCheque.persist();
System.out.println("add" + result.getErrorCount());// Zero when there are errors
return ssiCheque;
}

最后我有了 jQuery 代码:

    var formData = $("#formAddChecks :input").serializeArray();
$.ajax({
type: "POST",
url: "addCheck",
data: formData,
beforeSend: function ( xhr ) {
console.log("before Send");
},
error: function (request, status, error) {
console.log('Error ' + "\n" + status + "\n" + error);
},
success: function(data) {
console.log(data);
}
});

JSON 对象正确到达 Controller ,但我想使用实体 javax.annotations API 验证 JSON。我所看到的只是使用自定义 validator 和“重写”验证代码。

这是验证 JSON 的唯一方法吗?

提前致谢!

更新 1

我遵循了@James Massey 的建议,现在我的代码如下所示:

Controller

@RequestMapping(value = "/addCheck", method = RequestMethod.POST)
@ResponseBody
public SsiCheque addChecks(@Valid @RequestBody SsiCheque ssiCheque, BindingResult result) {

//ssiCheque.persist();
System.out.println("agregar " + result.getErrorCount());
return ssiCheque;
}

Javascript 文件

    var ssiCheque = {
cheNumero : $("#formAddChecks cheNumero").val(),
cheRecepto : $("#formAddChecks cheReceptor").val(),
cheMonto : $("#formAddChecks cheMonto").val(),
cheFecha : $("#formAddChecks cheFecha").val(),
cheConcepto : $("#formAddChecks cheConcepto").val()
};


$.ajax({
type: "POST",
contentType: "application/json",
url: "addCheck",
data: ssiCheque,
dataType: "json",
beforeSend: function ( xhr ) {
console.log("before Send");
},
error: function (request, status, error) {
console.log('Error ' /*+ request.responseText*/ + "\n" + status + "\n" + error);
},
success: function(data) {
console.log(data);
}
});

但是当我提交表单并执行 Ajax 函数 时,我收到了 400 错误(不正确的请求)。我以前遇到过这个错误,当时json对象格式和 Controller 规范不兼容,但这次我不知道为什么会出错。

再次感谢!

最佳答案

我已经用另一种方式解决了我的验证问题。假设我有代理对象:

public class Agent {
public int userID;
public String name;
public boolean isVoiceRecorded;
public boolean isScreenRecorded;
public boolean isOnCall;
}

我想验证:(1) 用户ID>0(2) 姓名为必填项(3) isVoiceRecorded 和isScreenRecorded 只有在isOnCall 为真时才能为真。

为此,我需要添加依赖项:

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>

现在看看 Agents 类的样子:

@NoArgsConstructor
@ToString
@EqualsAndHashCode(of = "userID")
@CheckBools
public class Agent {
@Min(0)
public int userID;
@NotNull(message = "Name cannot be null")
public String name;
public boolean isVoiceRecorded;
public boolean isScreenRecorded;
public boolean isOnCall;
public LocalDateTime startEventDateTime;
}

(1) @Min(0) - 解决 userID>0(2) @NotNull(message = "Name cannot be null") - 解决 name 是强制性的,你有如何指定错误消息的例子(3) 我定义的@CheckBools 注解,在类级别检查isVoiceRecorded 和isScreenRecorded 只有在isOnCall 为真时才能为真。

@Documented
@Constraint(validatedBy = MyConstraintValidator.class)
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface CheckBools {
String message() default "'isVoiceRecorded' or 'isScreenRecorded' can be true only if you are on call";

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

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

在下面的类中定义规则

public class MyConstraintValidator implements ConstraintValidator<CheckBools, Agent> {
@Override
public void initialize(CheckBools constraintAnnotation) {

}

@Override
public boolean isValid(Agent value, ConstraintValidatorContext context) {
if (!value.isOnCall && (value.isVoiceRecorded || value.isScreenRecorded))
return false;
else return true;
}
}

在 Controller 层:

@RestController
@RequestMapping("Myteamview")
public class MyteamviewController {
@Autowired
AgentInfo agentInfo;

@RequestMapping(path = "agents", method = RequestMethod.POST)
public ResponseEntity<Boolean> addOrUpdateAgent(@Valid @RequestBody Agent agent) {
ResponseEntity<Boolean> responseEntity = new ResponseEntity<>(agentInfo.addAgent(agent),HttpStatus.OK);
return responseEntity;
}
}

注意:重要的是你在@RequestBody代理之前指定@Valid

关于java - 如何在 Spring 4 MVC 中使用 javax.validation 和 JSON 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312554/

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