【发布时间】:2012-02-18 16:31:26
【问题描述】:
我有一个接受 JSON 请求的 REST 服务。我想验证传入的 JSON 请求值。我该怎么做?
在 Spring 3.1.0 RELEASE 中,我知道有人想确保他们使用3.1.13 New HandlerMethod-based Support Classes For Annotated Controller Processing 列出的最新支持类
旧的项目是:AnnotationMethodHandlerAdapter。我想确保我使用的是最新版本,例如 RequestMappingHandlerAdapter。
这是因为我希望它能解决我看到的问题:
java.lang.IllegalStateException:在没有前面的模型属性的情况下声明了错误/BindingResult 参数。检查您的处理程序方法签名!
我的@Controller处理方法和相关代码是这样的:
@Autowired FooValidator fooValidator;
@RequestMapping(value="/somepath/foo", method=RequestMethod.POST)
public @ResponseBody Map<String, String> fooBar(
@Valid @RequestBody Map<String, String> specificRequest,
BindingResult results) {
out("fooBar called");
// get vin from JSON (reportRequest)
return null;
}
@InitBinder("specificRequest") // possible to leave off for global behavior
protected void initBinder(WebDataBinder binder){
binder.setValidator(fooValidator);
}
FooValidator 看起来像这样:
@Component
public class FooValidator implements Validator {
public boolean supports(Class<?> clazz) {
out("supports called ");
return Map.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
out("validate called ");
}
private void out(String msg) {
System.out.println("****** " + getClass().getName() + ": " + msg);
}
}
如果我删除 BindingResult,一切正常,但我无法判断 JSON 是否经过验证。
对于 JSON 请求使用 Map<String, String> 或使用单独的验证器而不是带有验证注释的自定义 Bean(您如何为 JSON 请求执行此操作?)的概念,我并不强烈依赖。任何可以验证 JSON 请求的东西。
【问题讨论】:
-
我们认为,如果我们能够以某种方式确保我们使用的是较新的类,例如 RequestMappingHandlerAdapter,那么这可能会起作用。你是如何设置的,或者这个问题还有其他好的解决方案吗?
标签: java json validation rest spring-mvc