gpt4 book ai didi

java - 获取拒绝值 null spring 验证

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:01 25 4
gpt4 key购买 nike

嗨,在我的项目中,当我尝试验证表单时,即使验证失败,它也不会显示任何错误消息(即使表单未提交并进入验证失败 block )

这是我的代码

      /****************** Post Method *************/
@RequestMapping(value="/property", method = RequestMethod.POST)
public String saveOrUpdateProperty(@ModelAttribute("property") Property property,
BindingResult result,
Model model,
HttpServletRequest request) throws Exception {
try {
if(validateFormData(property, result)) {
model.addAttribute("property", new Property());
return "property/postProperty";


}
}


/********* Validate Block *************/
private boolean validateFormData(Property property, BindingResult result) throws DaoException {
if (property.getPropertyType() == null || property.getPropertyType().equals("")) {
result.rejectValue("propertyType", "Cannot Be Empty !", "Cannot Be Empty !");
}
if (property.getTitle() == null || property.getTitle().equals("")) {
result.rejectValue("title", "Cannot Be Empty !", "Cannot Be Empty !");
}
return (result.hasFieldErrors() || result.hasErrors());
}

但是当我调试时我可以看到下面的一个

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'property' on field 'title': rejected value [null]; codes [Cannot Be Empty !.property.title,Cannot Be Empty !.title,Cannot Be Empty !.java.lang.String,Cannot Be Empty !]; arguments []; default message [Cannot Be Empty !]

这就是我在jsp文件中显示的方式

<div class="control-group">
<div class="controls">
<label class="control-label"><span class="required">* </span>Property Type</label>
<div class="controls">
<form:input path="title" placeholder="Pin Code" cssClass="form-control border-radius-4 textField"/>
<form:errors path="title" style="color:red;"/>
</div>
</div>
</div>

当我在调试时看到下面的事件时(1 个错误是正确的)

org.springframework.validation.BeanPropertyBindingResult: 1 errors

为什么在jsp中不显示有人可以帮助我吗?

最佳答案

我认为您看不到任何内容,因为在下面的第二行您销毁了模型(包括验证错误)并创建了一个新模型。

    if(validateFormData(property, result)) {
model.addAttribute("property", new Property()); // <------
return "property/postProperty";

尝试显示作为参数传入的属性,也许您将能够看到验证错误。

    if(validateFormData(property, result)) {
model.addAttribute("property", property);
return "property/postProperty";

关于java - 获取拒绝值 null spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984618/

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