我愿意加入类似JSR303的验证,它可以识别相关的HttpServletRequest。
例如,Re-Captcha需要发送正在解决CAPTCHa的用户的IP以及挑战和响应,为此,我需要类似HttpServltRequest.getRemoteAddr()的东西,因此为了验证表单,包含带有注释的ReCAPTCHa /控制器的相应验证器(例如,使用类似@ReCaptcha的东西注释POJO ),我需要在验证层中使用这样的实例。
理想情况下,我希望将验证逻辑注入到
[Http Servlet Request] -> [Jackson or similar data bind of request parts to POJO]和
@RequestMapping("somewhere")
@ResponseBody
public Object login(@Valid @RequestBody LoginData loginData) {
...
}打电话。
有哪些Spring工具可以实现这样的验证?
我发现,在形成HttpServletRequest之后,在将请求数据绑定到对象之前,HandlerInterceptor概念的行为有点超出了我的预期。
发布于 2014-10-19 00:13:05
看起来我找到了一些有用的东西:
在controller的类中,添加
@InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
binder.addValidators(new ReCaptchaValidator(request));
}此@InitBinder-annotated方法将在每个控制器@RequestMapping-methods之前调用。您可以通过提供要触发的模型属性名称列表作为注释值来改进此选择。
而ReCaptchaValidator仅仅是org.springframework.validation.Validator接口的一个实现。
正如文档所述,可以在此@InitBinder-method中使用的参数类似于@RequestMapping控制器方法:
* <p>Such init-binder methods support all arguments that {@link RequestMapping}
* supports, except for command/form objects and corresponding validation result
* objects. Init-binder methods must not have a return value; they are usually
* declared as {@code void}.
*
* <p>Typical arguments are {@link org.springframework.web.bind.WebDataBinder}
* in combination with {@link org.springframework.web.context.request.WebRequest}
* or {@link java.util.Locale}, allowing to register context-specific editors.https://stackoverflow.com/questions/26434811
复制相似问题