您可以根据您想要执行的模型和验证来实现“org.springframework.validation.Validator”。您可以在控制器中使用 InitBinder 来验证请求对象。下面是我使用我的一个项目的一个例子:
@Component(value = "fromToDateValidator")
public class FromToDateValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return (InventorySearchRequestByDate.class.equals(clazz) || OrderRequestDetails.class.equals(clazz));
}
@Override
public void validate(Object target, Errors errors) {
if (!errors.hasErrors()) {
Date fromDate = null;
Date toDate = null;
if (target instanceof InventorySearchRequestByDate) {
fromDate = ((InventorySearchRequestByDate) target).getFromDate();
toDate = ((InventorySearchRequestByDate) target).getToDate();
} else if (target instanceof OrderRequestDetails) {
fromDate = ((OrderRequestDetails) target).getFromDate();
toDate = ((OrderRequestDetails) target).getToDate();
}
if (fromDate.compareTo(toDate) > 0) {
errors.rejectValue("toDate", null, "To Date is prior to From Date");
}
}
}
}
所以,支持方法取类参数,检查类验证是否适用于模型。所以就像在我的示例中,我必须检查 InventorySearchRequestByDate 请求对象或 OrderRequestDetails 请求对象,所以我根据日期执行了检查。
现在在 validate 方法中包含用于验证模型和添加错误的核心逻辑。
你可以像下面这样在你的控制器中绑定这个验证器并使用它:
@RestController
public class ItemInventoryController extends BaseController {
@Autowired
@Qualifier("fromToDateValidator")
private Validator fromToDateValidator;
@Autowired
private ItemInventoryService itemInventoryService;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.addValidators(fromToDateValidator);
}
@RequestMapping(value = WebServiceEndPoints.INVENTORY_AVAILABILITY_BY_DATE, method = RequestMethod.POST)
public Map<String, Set<ItemDetails>> getAvailableItems(@RequestBody @Validated InventorySearchRequestByDate
inventorySearchRequestByDate, BindingResult bindingResult) throws InvalidFieldException {
validRequest(bindingResult);
return itemInventoryService.searchItemsByDateAvailablity(inventorySearchRequestByDate.getFromDate()
, inventorySearchRequestByDate.getToDate());
}
public void validRequest(BindingResult bindingResult) throws InvalidFieldException {
if (bindingResult.hasErrors()) {
throw new InvalidFieldException(bindingResult.getFieldErrors());
}
}
}
所以上面的代码会根据你的全局处理程序验证模型并抛出异常体。