gpt4 book ai didi

java - Spring向数据库添加数据,BindingResult结果有Errors

转载 作者:行者123 更新时间:2023-12-01 18:11:57 25 4
gpt4 key购买 nike

我试图将代理添加到我的数据库中,它检测到结果有错误,因此不会添加到数据库中,我怀疑这是因为 BindingResult 不起作用。

表单代码:

 <form:form method="POST" action="/AgentsCRUD/agent/addAgent" modelAttribute="agent">
<table>
<tr>
<td><form:label path="agentId"><spring:message code="label.agentId" /></form:label></td>
<td><form:input path="agentId"/></td>
<td style="color:red"><form:errors path="agentId"/> </td>
</tr>
<tr>
<td><form:label path="name"><spring:message code="label.name" /></form:label></td>
<td><form:input path="name" /></td>
<td style="color:red"><form:errors path="name"/> </td>
</tr>
<tr>
<td><form:label path="phone"><spring:message code="label.phone" /></form:label></td>
<td><form:input path="phone"/></td>
<td style="color:red"><form:errors path="phone"/> </td>
</tr>
<tr>
<td><form:label path="fax"><spring:message code="label.fax" /></form:label></td>
<td><form:input path="fax"/></td>
<td style="color:red"> <form:errors path="fax"/> </td>
</tr>
<tr>
<td><form:label path="email"><spring:message code="label.email" /></form:label></td>
<td><form:input path="email"/></td>
<td style="color:red"> <form:errors path="email"/> </td>
</tr>
<tr>
<spring:message code="submit.button" var="labelSubmit"></spring:message>
<td><input type="submit" value="${labelSubmit}"/></td>
</tr>
</table>

Controller 中的代码是:

@PostMapping("/addAgent")
public ModelAndView addAnAgent(ModelMap model, @Valid @ModelAttribute("agent") Agents agent, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("/addAgent");
}
service.addAnAgent(agent);
return new ModelAndView("redirect:/agent");
}

该服务的代码是:

   public void addAnAgent(Agents agent) {
EntityManager em = DBUtil.getEMF().createEntityManager();
EntityTransaction trans = em.getTransaction();
try {
trans.begin();
em.persist(agent);
trans.commit();
} catch (Exception ex) {
System.out.println(ex);
} finally {
em.close();
}
}

最佳答案

发现我在数据库中有额外的表,我不知道,在jsp中获取这些值修复了它

             <tr>
<td><form:label path="username"><spring:message code="label.username" /></form:label></td>
<td><form:input path="username"/></td>
<td style="color:red"> <form:errors path="username"/> </td>
</tr>
<tr>
<td><form:label path="password"><spring:message code="label.password" /></form:label></td>
<td><form:input path="password"/></td>
<td style="color:red"> <form:errors path="password"/> </td>
</tr>

关于java - Spring向数据库添加数据,BindingResult结果有Errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455003/

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