gpt4 book ai didi

spring - 如何使用 BindingResult 检查特定行是否存在 Spring 中多行验证的验证错误

转载 作者:行者123 更新时间:2023-12-01 04:53:20 25 4
gpt4 key购买 nike

当前逻辑将检查 BindingResult 是否有错误,并在 jsp 中显示数据和错误。
需要的逻辑是检查每一行的错误并仅显示那些包含验证错误的行并更新没有验证错误的行。
@自动连线
私有(private) IncidentExtractStgService eventExtractStgService;

@RequestMapping(value = "/validatingIncidentList", method = RequestMethod.POST)
public String ValidateIncidentList( @Valid @ModelAttribute("incidentsForm") IncidentsForm incidentsForm,
BindingResult bindingResult,RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {


for(ObjectError error: bindingResult.getAllErrors()){

System.out.println(error);
}

redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.incidentsForm", bindingResult);
redirectAttributes.addFlashAttribute("incidentsForm", incidentsForm);

return "redirect:/validateIncidentList";
}
else
{
for(IncidentExtractStg ie : incidentsForm.getIncidents()) {

ie.setValidated(1);
incidentExtractStgService.update(ie);

System.out.println(ie.getNumber()+" "+ie.getWaitTime());
}


return "redirect:/validateIncidentList";

}

下面的代码片段将检查模型是否包含属性“incidetsForm”,如果是,则将其发送到 example.jsp,然后将显示数据和验证错误。
@RequestMapping(value = "/validateIncidentList", method = RequestMethod.GET)
public String incidentList(Model model) {
if (!model.containsAttribute("incidentsForm")) {
List<IncidentExtractStg> incidents = incidentExtractStgDao.validateList();
incidentsForm.setIncidents(incidents);
model.addAttribute("incidentsForm", incidentsForm);
return "example";
}

model.addAttribute("errormessage","Please Check the Validation Errors column for Errors");
return "example";
}

Example.jsp 代码片段
<c:forEach var="ie" items="${incidentsForm.incidents}" varStatus="status">
<tr>
<td><form:input path="incidents[${status.index}].id" value="${ie.id}" readonly ="true"/></td>
<td><form:errors path="incidents[${status.index}].id" cssClass="error" /></td>

<td><form:input path="incidents[${status.index}].number" value="${ie.number}"/></td>
<td><form:errors path="incidents[${status.index}].number" cssClass="error" /></td>
</tr>

IncidentsForm.java:
import java.util.List;
import javax.validation.Valid;

import com.infosys.sla.model.IncidentExtractStg;

public class IncidentsForm {

@Valid
private List<IncidentExtractStg> incidents;



public List<IncidentExtractStg> getIncidents() {
return incidents;
}


public void setIncidents(List<IncidentExtractStg> incidents) {

this.incidents = incidents;
}
}

IncidentExtractStg.java 片段
@Entity
@Table(name="incident_extract_stg")
public class IncidentExtractStg {

@Id
@Column(name="ies_id")
private int id;

@NotBlank(message="number cannot be empty")
@Pattern(regexp="[A-Za-z0-9]*",message="number can contain only alphabets and numbers")
@Column(name="ies_number")
private String number;

最佳答案

首先,如果我是你,我将提取服务层中的所有逻辑。要继续,您可以创建一个接口(interface) IncidentService以及它自己的具体实现IncidentServiceImpl您可以在其中安全地处理您的需求。 Controller 绝对不会做所有事情。

那么,你的需求是什么?
“检查每一行的错误并仅显示那些包含验证错误的行并更新没有验证错误的行”

服务层中的方法可能是这样的:

public void handleErrors(IncidentsForm incidentsForm, BindingResult bindingResult){ 

List<String> fieldsInErrorState = new ArrayList<String>(10);

if (bindingResult.hasErrors()) { //
Map<String, Object> bindingModel = bindingResult.getModel();

for (Map.Entry<String, Object> entry : bindingModel.entrySet()) {
String key = entry.getKey();
//Object value = entry.getValue(); you don't need to parse that unless you want specific domain model handlers to run

//you need to store the key as a form field which is in error state
fieldsInErrorState.add(key);

//you already have all the stuff to parse and display errors in your JSP
//thanksfully to bindingResult and JSTL tags.
}

ContactMessageForm cmForm2 = new ContactMessageForm();
// get the list of the fields inside your form
Field[] declaredFields = ContactMessageForm.class.getDeclaredFields();
for (Field field : declaredFields) {
if (!fieldsInErrorState.contains(field.getName())) {
if (field.getName().equalsIgnoreCase("firstname")) {
cmForm2.setFirstname(contactMessageForm.getFirstname());
}
if (field.getName().equalsIgnoreCase("lastname")) {
cmForm2.setLastname(contactMessageForm.getLastname());
}

//etc for each properties of your form object.
}

// then store your dbmodel object
// BUT i think you must be carefull to your data integrity... It is maybe not safe to save an object like that with bypassing some stuff...
// Your form was built like that maybe for a good reason looking at your objects graph.
// If your form is too big, then split it in small parts, it will be much easy to handle, to update, and to work with daily.
}

}


}

当然您需要自定义该代码,不要忘记添加 throws IntrospectionException到你的服务方法,你在好路上。

干杯!

关于spring - 如何使用 BindingResult 检查特定行是否存在 Spring 中多行验证的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182327/

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