首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HttpServletRequest感知的类Spring JSR303验证

使用HttpServletRequest感知的类Spring JSR303验证
EN

Stack Overflow用户
提问于 2014-10-18 07:36:15
回答 1查看 1.1K关注 0票数 0

我愿意加入类似JSR303的验证,它可以识别相关的HttpServletRequest

例如,Re-Captcha需要发送正在解决CAPTCHa的用户的IP以及挑战和响应,为此,我需要类似HttpServltRequest.getRemoteAddr()的东西,因此为了验证表单,包含带有注释的ReCAPTCHa /控制器的相应验证器(例如,使用类似@ReCaptcha的东西注释POJO ),我需要在验证层中使用这样的实例。

理想情况下,我希望将验证逻辑注入到

代码语言:javascript
复制
[Http Servlet Request] -> [Jackson or similar data bind of request parts to POJO]

代码语言:javascript
复制
@RequestMapping("somewhere")
@ResponseBody
public Object login(@Valid @RequestBody LoginData loginData) {
    ...
}

打电话。

有哪些Spring工具可以实现这样的验证?

我发现,在形成HttpServletRequest之后,在将请求数据绑定到对象之前,HandlerInterceptor概念的行为有点超出了我的预期。

EN

回答 1

Stack Overflow用户

发布于 2014-10-19 00:13:05

看起来我找到了一些有用的东西:

在controller的类中,添加

代码语言:javascript
复制
@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控制器方法:

代码语言:javascript
复制
* <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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26434811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档