[英]Spring boot validation doesn't work
我有Spring啟動應用程序,我無法向用戶顯示錯誤消息。 沒有該數據的對象不會保存在數據庫中,這沒關系。 但顯示錯誤消息是問題所在。 當我調試我得到錯誤大小= 0
這是我的模特:
@Size(min = 1, message = "Address is invalid.")
@NotNull
@Column
private String address;
調節器
@RequestMapping(value = "/create", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createNewBusiness(@Valid @ModelAttribute("business")
Business business, BindingResult result, Model model) {
model.addAttribute("userEmail", getUserEmail());
logger.info("/business/create:" + business.toString());
LocationResponse locationResponse = geoService.getCoords(business.getAddress());
if(locationResponse.getStatus().equals("OK")) {
business.setLatitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLat());
business.setLongitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLng());
business.setUserId(getUserId());
businessService.createNew(business);
model.addAttribute("business", business);
}else{
business.setAddress(null);
model.addAttribute("business", business);
}
if(result.hasErrors()){
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
}
return "newBusiness";
}
return "business";
}
和Thymeleaf
<div class="input-field left m-0 w-100">
<i class="fa fa-map-marker prefix grey-text" aria-hidden="true"></i>
<input placeholder="Address" id="inputAddress" name="address" type="text" class="validate my-0" th:required="true">
<label th:errors="*{address}" th:if="${#fields.hasErrors('address')}" >Invalid address </label>
</div>
你需要使用@Valid
和@ModelAttribute
來創建createNewBusiness()
的參數 - 這取決於你的參數和東西。
您還需要將th:field="*{adress}"
adress th:field="*{adress}"
到inputfield,因為它是框架中此輸入字段的ID。
所以在你的情況下,方法標題將如下所示:
public String createNewBusiness(@ModelAttribute Business business,
@Valid Model model, BindingResult result) {
// ...
}
如果要拋出自定義驗證錯誤(例如,如果您通過模型中的注釋驗證器以外的其他方式驗證字段),則可以通過BindingResult#rejectValue()
方法執行此操作。 例如:
if (business.getEmail() == null || business.getEmail().length() == 0) {
result.rejectValue("email", "email.missing", "Must enter email");
}
顯然,電子郵件字段只是一個示例,因為您需要在thymeleaf資源上的電子郵件字段以及錯誤字段。
有關此主題的更多信息, 請訪問https://docs.spring.io/autorepo/docs/spring-framework/3.2.8.RELEASE/javadoc-api/org/springframework/validation/Errors.html#rejectValue(java.lang.String ,%20java.lang.String,%20java.lang.Object [],%20java.lang.String)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.