Spring mvc @InitBinder not called when processing ajax request

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

when processing a regular 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(); } 

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

0
source share
1 answer

Yes, this is the correct behavior - annotated @InitBinder methods are only called when arguments that require binding are resolved, so in your case, if you have an @RequestMapping / @ModelAttribute with arguments like your command / model object that needs to be bound , then @InitBinder will be called.

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

+1
source

Source: https://habr.com/ru/post/1264498/


All Articles