0
我一直在使用Spring MVC和hibernate annotations來驗證傳入的請求對象,並且在我需要驗證傳入集合之前,這一切都很好。spring mvc驗證器@valid不適用於集合
@RequestMapping(value = "/guests", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Set<GuestResource>> postGuestsToAttendance(
@Valid @RequestBody Set<RequestToAddGuest> guestRequests) throws FieldValidationException,
RequestBodyResourceBadRequestException
正如我想的那樣,它試圖對Set本身進行驗證,而不是對其內部的各個成員執行驗證。
經過一番研究,我找不到任何'簡單'的解決方案,而是在自定義驗證器上找到了一些並調用它們。由於我不需要自定義驗證器,只是爲集合中的每個項目調用驗證的方法,所以我試圖讓所有工作都成功,但無濟於事。我究竟做錯了什麼?
這裏是我的調用代碼:
for (RequestToAddGuest guestRequest : guestRequests) {
// Perform validation
BindingResult bindingResults = new DirectFieldBindingResult(guestRequest, RequestToAddGuest.class.getName());
validator.validate(guestRequests, bindingResults);
checkForErrors(bindingResults);
}
這裏是checkForErrors代碼。當我在一個單獨的對象上使用@Valid時,它工作得很好。
protected void checkForErrors(BindingResult results) throws FieldValidationException {
if (results.hasErrors()) {
FieldValidationException exception = new FieldValidationException();
exception.setFieldErrors(results.getFieldErrors());
throw exception;
}
}
以供參考,在這裏是RequestToAddGuest類驗證註釋:
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.SafeHtml;
public class RequestToAddGuest {
@NotEmpty
@SafeHtml
public String firstName;
@SafeHtml
@NotEmpty
public String lastName;
@SafeHtml
public String emailAddress;
@SafeHtml
public String streetLine1;
@SafeHtml
public String streetLine2;
@SafeHtml
public String streetLine3;
@SafeHtml
public String city;
@SafeHtml
public String stateCode;
@SafeHtml
public String zip;
@SafeHtml
public String countryCode;
@SafeHtml
public String phoneArea;
@SafeHtml
public String phoneNumber;
@SafeHtml
public String phoneExtension;
}