Spring REST服务控制器未被@PathVariable和@Valid验证

时间:2016-06-16 02:56:21

标签: spring rest validation

@Controller
@EnableWebMvc
@Validated
public class ChildController extends ParentController<InterfaceController> implements InterfaceController{

    @Override
    @RequestMapping(value = "/map/{name}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody   
    public List<Friends> getAllFriendsByName(
        @Valid
        @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters")
        @PathVariable("name") String name,
        @RequestParam(value="pageSize", required=false) String pageSize,
        @RequestParam(value="pageNumber", required=false) String pageNumber,            
        HttpServletRequest request) throws BasicException {

    //Some logic over here;

    return results;
    }

@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleResourceNotFoundException(ConstraintViolationException e) {
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    StringBuilder strBuilder = new StringBuilder();
    for (ConstraintViolation<?> violation : violations ) {
        strBuilder.append(violation.getMessage() + "\n");
    }
    return strBuilder.toString();
}

嗨,我正在尝试对spring请求参数进行相当基本的验证,但它似乎没有调用Exception处理程序,有人能指出我正确的方向

P.S。我一直得到NoHandlerFoundException

1 个答案:

答案 0 :(得分:1)

Spring不支持@PathVariable使用@Valid进行验证。但是,您可以在处理程序方法中进行自定义验证,或者如果您坚持使用@Valid然后编写自定义编辑器,将路径变量值转换为对象,使用JSR 303 bean验证然后在该对象上使用@Valid 。这可能确实有效。

修改 这是第三种方法。实际上,您可以使用spring来将路径变量视为模型属性,然后对其进行验证。 1.为路径变量编写自定义验证器 2.为您的路径变量构建@ModelAttribute,然后使用@Validator(是的不是@Valid,因为它不允许您在该模型属性上指定验证程序。)

@Component
public class NameValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return String.class.equals(clazz);
    }
    @Override
    public void validate(Object target, Errors errors) {
        String name = (String) target;
        if(!StringUtils.isValidName(name)) {
            errors.reject("name.invalid.format");
        }
    }
}

@RequestMapping(value = "/path/{name}", method = RequestMethod.GET)
public List<Friend> getAllFriendsByName(@ModelAttribute("name") @Validated(NameValidator.class) String name) {
    // your code

    return friends;
}

@ModelAttribute("name")
private String nameAsModelAttribute(@PathVariable String name) {
    return name;
}