我们的动作类中直接提供validate()
方法,我们可以在其中使用自己的逻辑来执行我们需要的某种验证。
例如,如果我需要验证有关日期时间的两个字段,我可以将自己的逻辑放在validate()
方法中,如下所示。
public final class DiscountAction extends ActionSupport implements ValidationAware, ModelDriven<Discount>
{
private Discount entity=new Discount();
@Override
public Discount getModel() {
return entity;
}
@Override
public void validate()
{
if(entity.getDiscountStartDate()!=null&&entity.getDiscountEndDate()!=null)
{
final int period=30;
final DateTime startDate=entity.getDiscountStartDate().withZone(DateTimeZone.forID("Asia/Kolkata")).withMillisOfSecond(0);
final DateTime endDate=entity.getDiscountEndDate().withZone(DateTimeZone.forID("Asia/Kolkata")).withMillisOfSecond(0);
final DateTime currentDate=new DateTime(DateTimeZone.forID("Asia/Kolkata"));
final int daysBetween = Days.daysBetween(startDate, endDate).getDays();
if(startDate.isAfter(endDate))
{
addFieldError("discountStartDate", "The start date must be earlier than the end date.");
}
else if(startDate.equals(endDate))
{
addFieldError("discountEndDate", "Both the dates can not be same.");
}
else if(DateTimeComparator.getDateOnlyInstance().compare(currentDate, endDate)==0 || endDate.isBefore(currentDate))
{
addFieldError("discountEndDate", "Can not be today's date or any day before today.");
}
else if(Days.daysBetween(startDate, endDate).getDays()<1)
{
addFieldError("discountEndDate", "There must be an interval of at least one day.");
}
else if(daysBetween>period)
{
addFieldError("discountEndDate", "The discount period is valid only upto "+period+(period==1?" day":" days")+" period which it excceds. The actual difference is "+daysBetween);
}
}
}
}
假设entity
是模型类的实例。
为什么我们需要自定义验证器?我还没有尝试过自定义验证器,因为它还不需要。
您能否向我展示一个真正需要定制验证器的真实情况/示例?
答案 0 :(得分:3)
自定义验证器用于:
validate
方法中重复使用它自定义验证程序的业务逻辑应该已作为单独的实体存在。它应该不作为嵌入在动作中的代码存在;它使得动作和验证都更难以测试。
当逻辑位于适当的位置时,它很容易在 验证器或 validate
方法中使用。优点是可以在XML和/或注释中轻松重复使用。
答案 1 :(得分:1)
在这样的point-of-view
中,我也可以声称不需要Struts2,因为我可以使用C ++实现我的Web应用程序。你能接受吗?我认为不行,因为使用MVC模式,如Struts2使您的应用程序更加干净和可维护。此外,您不必在实施时再次重做。
同样,如果您想使用已经实施和测试的最佳做法,并且如果您希望通过不从头开始做事来节省时间和金钱,并且如果您希望使用可维护代码分离的问题 ...然后您需要使用Struts2 custom validators
而不是那种丑陋的validate
方法(这很难看,因为aspects
此类验证不应与业务逻辑混合 - 见AOP)。