@RequestBody和自定义org.springframework.validation.Validator

时间:2014-03-21 09:37:50

标签: ajax json spring spring-validator

我有控制器接收这样的json对象:"fields" : ["abc","one","two","three"]

@RequestMapping(value="submit.controller", produces="application/json",
        consumes="application/json", method = RequestMethod.POST)
public View submit(@RequestBody Form form) {
    // populating view;
    return view;
}

以下表格:

public class Form {

    private List<String> fields;

    public List<String> getFields(){
        return fields;
    }

    public setFields(List<String> fields){
        this.fields= fields;
    }
}

验证员:

public class CustomValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Form.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Form form = (Form) target;
        // some complexity validation
    }

}

和处理程序:

@ExceptionHandler
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleMethodArgumentNotValidException(
        MethodArgumentNotValidException error) {
    return error.getBindingResult();
}

我的目标是通过我的自定义验证程序验证Form,而不使用注释@Valid,例如它在我的情况下不起作用(添加<mvc:annotation-driven />需要很多重构)。

如果没有控制器中的 BindingResult ,该如何实现?

0 个答案:

没有答案