gpt4 book ai didi

java - JSP 和 Spring 验证

转载 作者:行者123 更新时间:2023-12-01 13:18:16 26 4
gpt4 key购买 nike

这是我的BackupForm :

public class BackupForm {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}

这是 validator :

@Component
public class BackupFormValidator implements Validator {

public boolean supports(Class<?> clazz) {
return BackupForm.class.isAssignableFrom(clazz);
}


public void validate(Object target, Errors errors) {
BackupForm backupForm = (BackupForm) target;

if (backupForm.getName().length() == 0) {
System.out.println("Empty");
errors.rejectValue("name", "name.empty", "Name field is empty.");
} else {
File file = new File(Configures.getDirectory() + "\\"
+ backupForm.getName() + ".sql");
if (file.exists()) {
System.out.println("Exists");
errors.rejectValue("name", "name.exist",
"File." + backupForm.getName() + ".sql already exists.");
}
}

}
}

这就是我在 Controller 中的做法:

@RequestMapping(value = "/backup", method = RequestMethod.POST)
public String backupProcess(
@ModelAttribute("backup") BackupForm backupForm,
BindingResult result, Map<String, Object> map) {

backupFormValidator.validate(backupForm, result);
if (result.hasErrors()) {
// Если обнаружилась ошибка, то добавим в карту идентификатор об
// ошибке и вернем логическое представление поиска
map.put("error", true);
map.put("backup", new BackupForm());
map.put("search", new SearchForm());
return "backup";

} else {
return "redirect:/";
}

}

它可以工作,但是标签 errors不工作:

<form:form method="POST" commandName="backup">
<c:if test="${!empty error}">
<div class="alert alert-danger">
<b>Can not execute command!</b>
<form:errors path="name" />
</div>
</c:if>

<div class="panel panel-default">
<div class="panel-heading">New backup</div>
<div class="panel-body">

<table style="width: 100%; border-collapse: collapse;">
<tbody>
<tr>
<td
style="vertical-align: top; width: 250px; letter-spacing: 0px; word-spacing: 0px;"><form:input
path="name" class="form-control input-sm" type="text"
placeholder="Enter backup name..." value="${name}" /></td>
<td
style="text-align: left; vertical-align: top; letter-spacing: 0px; word-spacing: 0px;">
&nbsp;&nbsp;&nbsp;<input class="btn btn-success btn-sm"
type="submit" value="Backup" />
</td>
</tr>
</tbody>
</table>

</div>
</div>
</form:form>

怎么了?验证工作正常,但是 <form:errors path="name" />不返回任何内容。

最佳答案

您应该删除以下行:

map.put("backup", new BackupForm());

这一行将 modelAttribute 重置为新的,因此不会出现错误。

关于java - JSP 和 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284071/

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