使用Spring @Validated Annotation验证获取请求路径变量

时间:2017-09-24 21:06:36

标签: java spring validation spring-boot

我正在尝试使用Spring Validator和@Validated注释来验证Get Request参数,但无法运行验证程序。我正在使用ModelAttribute来尝试让验证器在Path Variable而不是Request Body上运行。是否可以在Get Request Path Variable上运行验证器?

这是我的控制器类和方法

@RestController
public class ProfileController {

    @RequestMapping(value = "/profile/{param}", method = RequestMethod.GET)
    public IVRProfile getProfile(@Validated(ParamValidator.class) @ModelAttribute("param") String param) {

    return sampleProfile();
    }

    @ModelAttribute("param")
    public String paramAsModelAttribute(@PathVariable String param) {
        return param;
    }

}

还有Validator类

@Component
public class ParamValidator implements Validator
{

    @Override
    public boolean supports(Class<?> clazz)
    {
        System.out.println("Validator supports test");
        return String.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors)
    {
        System.out.println("Validator Test");
        // Validation code

    }

}

点击端点时都不会执行print语句。

对于我可能缺少或做的不同的任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

您可以实现以下所需的验证功能。

public class ParamValidator implements ConstraintValidator<ParamConstraint, String> {

    @Override
    public void initialize(ParamConstraint paramConstraint) {
    }

    @Override
    public boolean isValid(String paramField, ConstraintValidatorContext cxt) {
        //Perform paramField validation
        return true;
    }
}

-

@Documented
@Constraint(validatedBy = ParamValidator.class)
@Target( { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ParamConstraint {

    String message() default "Default validation message";

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

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

-

@RequestMapping(value = "/profile/{param}", method = RequestMethod.GET)
public IVRProfile getProfile(@Valid @ParamConstraint @ModelAttribute("param") String param) {
    return sampleProfile();
}

最后不要忘记用@Validated注释Controller。

@RestController
@Validated
public class ProfileController {
    //...
}

您可以在提及here的示例中找到更多详细信息。

答案 1 :(得分:-1)

如果您想获得status这样的单一RequestParams,可以按照以下代码强制执行。

@RestController
public class ProfileController {

    @RequestMapping(value = "/profile/{param}", method = RequestMethod.GET)
    public IVRProfile getProfile(@RequestParam(name = "status", required = true) String status, @ModelAttribute("param") String param) {}

}

如果你想强制使用PathVariable,那么就这样做。

@RestController
public class ProfileController {

    @RequestMapping(value = "/profile/{param}", method = RequestMethod.GET)
    public IVRProfile getProfile(@PathVariable(name = "param", required = true) String param, @ModelAttribute("param") String param) {}

}

希望这项工作!!!