【问题标题】:When does databinding and validation occur in spring mvc?spring mvc中什么时候发生数据绑定和验证?
【发布时间】:2014-12-23 20:58:09
【问题描述】:

我最近通过 Spring MVC 文档了解了 DispatcherServlet 下的请求处理流程

1)创建请求上下文

2)通过准备好的处理程序映射找到处理程序/控制器 上下文启动

3)如果已配置,则执行 Interceptors preHandler 方法

4)执行Handler/Conroller方法

5)如果已配置,则执行拦截器 postHandler 方法

6) 处理异常(如果有)

7)渲染视图

8)如果已配置,则在完成方法后执行拦截器

现在我有以下方法

    @RequestMapping(value="/userHistory", method=RequestMethod.GET)
    public @ResponseBody UserDetails getUserHistory(Model model, @valid UserDetail userDetail HttpServletRequest request, HttpServletResponse response) {
      model.addAttribute("userDetail", new userDetail());
    }

我的问题是在上述请求处理流程中的什么时间点,DispatcherServlet 将请求中的数据绑定到模型和 userDetail 对象?

类似地,dispacherservlet 在什么时候触发对带有有效注释的 UserDetail 对象的验证?

更新:- 假设我已经像这样在控制器方法下设置了 customValidator。现在在什么时间点customValidation InitBinder 会被执行吗?

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setValidator(customValidator);
    }

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    在步骤 3 和 4 之间。数据绑定由参数解析器处理。那些也负责验证。

    在您的示例中,您有参数@valid UserDetail userDetail。 Spring 对该参数使用的默认解析器是ServletModelAttributeMethodProcessor。它将传入的表单数据绑定到UserDetail 实例,如果存在@Valid@Validated 注释,它还会验证对象。这意味着验证不是一个单独的步骤,而是由参数解析器处理或根本不处理。

    在所有参数解析器都已执行后,处理程序方法将使用已解析的参数调用。

    【讨论】:

    • initBinder 在参数解析器之前执行,因为绑定器被(其中一些)使用。验证器仍由参数解析器调用(可能通过活页夹间接调用)。
    • 所以你的意思是说Initbinder方法在步骤3和4之间执行。然后我们在initBinder下注册了customValidator。完成验证后,将在绑定结果下添加错误。对吗?
    • @user3198603 initBinder 只是一个设置。你可以定义事情是如何完成的,比如“使用这个验证器”或“不绑定这个属性”。实际工作由答案中描述的参数解析器完成。
    猜你喜欢
    • 2013-02-09
    • 2018-08-27
    • 2017-02-18
    • 2011-06-23
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多