处理ajax请求时未调用spring mvc @InitBinder [英] spring mvc @InitBinder is not called when processing ajax request

查看:98
本文介绍了处理ajax请求时未调用spring mvc @InitBinder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@InitBinder
public void initBinder(WebDataBinder binder) {
    this.binder = binder;
}

在处理普通请求时,可以调用该函数,但是如果第一个请求是ajax请求

when processing the normal request , the function can be called , but if the first request is an ajax request

@RequestMapping("create")
@ResponseBody
public String create(@RequestBody String body) {
    JSONObject result = new JSONObject();
    try{
        JSONObject params = new JSONObject(body);
        T t = buildEntity(params);
        service().save(t);
        result.put(ExtConstant.DATA, t.detailJson());
        result.put(ExtConstant.SUCCESS, true);
    }catch(Exception e){
        result.put(ExtConstant.SUCCESS, false);
        result.put(ExtConstant.ERROR_MSG, e.getMessage());
        e.printStackTrace();
    }
    return result.toString();
}

未调用函数initBinder,活页夹为null.真让我困惑

the function initBinder is not been called , the binder is null . that really confuse me

推荐答案

是的,这是正确的行为- @InitBinder 注释的方法仅在需要绑定的参数被解析时才调用,因此在您的情况是,如果您有一个 @RequestMapping / @ModelAttribute 方法,其参数如您的command/model对象需要绑定,则将调用 @InitBinder

Yes, that is the correct behavior - @InitBinder annotated methods are only called when arguments that need binding are being resolved, so in your case if you had a @RequestMapping/@ModelAttribute method with arguments like your command/model object which require binding then @InitBinder will be called.

在这种特定情况下,您的 create 方法具有一个以 @RequestBody 注释的参数主体,该参数不是由绑定器解析的,而是由MessageConverters(来自json/xml转换为适当的类型),因此不会调用 @InitBinder 方法.

In this specific case your create method has an argument body which is annotated with @RequestBody, this argument is not resolved by the binder but the MessageConverters(from json/xml to the appropriate type), and so the @InitBinder method is not called.

这篇关于处理ajax请求时未调用spring mvc @InitBinder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆