使用@Annotations验证@RequestParam

时间:2014-06-22 22:30:22

标签: spring spring-mvc annotations

我正在尝试验证参数的@RequestParam。这是我的控制器:

@RequestMapping(value = "/addCategory", method = RequestMethod.POST)
public ModelAndView addCategory(@ValidCategoryName @RequestParam(value = "categoryName") String categoryName) {
    ModelAndView modelAndView = new ModelAndView();

    boolean addedSuccessfully = sideViewControllerDelegate.addMenuCategory(categoryName);

    modelAndView.setViewName("home_partial/side_view/category_completed");
    if (addedSuccessfully) {
        modelAndView.addObject("responseMessage", "ADDED");
    }
    return modelAndView;
}

并且@ValidCaegoryName的定义如下:

@Target({METHOD, FIELD, ANNOTATION_TYPE, PARAMETER})
@Retention(RUNTIME)
@Documented
@NotNull
@Constraint(validatedBy = ValidCategoryImpl.class)
public @interface ValidCategoryName {
        String message() default "This Category Does not Seem to Allowed";

        Class<?>[] groups() default { };

        Class<? extends Payload>[] payload() default { };

        int min() default 30;
}

我的Impl课程是这样的:

public class ValidCategoryImpl implements ConstraintValidator<ValidCategoryName, String> {

    @Autowired
    MenuCategoriesService menuCategoriesService;

    private int min;

    @Override
    public void initialize(ValidCategoryName constraintAnnotation){
        min = constraintAnnotation.min();
    }

    @Override
    public boolean isValid(String categoryName, ConstraintValidatorContext context){
        return categoryName.length() < min && menuCategoriesService.containsCategoryName(categoryName);
    }
}

我错过了什么吗?

谢谢!

0 个答案:

没有答案