【发布时间】:2014-10-13 17:59:15
【问题描述】:
我的方法中有一个 @RequestBody 注释参数,如下所示:
@RequestMapping(value = "/courses/{courseId}/{name}/comment", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody CommentContainer addComment(@PathVariable Long courseId,
@ActiveAccount Account currentUser,
@Valid @RequestBody AddCommentForm form,
BindingResult formBinding,
HttpServletRequest request) throws RequestValidationException {
.....
}
然后我在同一个控制器中有一个@InitBinder注解的方法:
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(AddCommentForm.class, new StringEscapeEditor());
}
我的StringEscapeEditor 没有运行。但我的initBinder 方法是。所以它不会将我的表单映射到转义编辑器。这似乎是在阅读此线程之后(@InitBinder 似乎不支持@RequestMapping):
spring mvc @InitBinder is not called when processing ajax request
我测试了映射@PathVariable 字符串,然后我的编辑器正在工作。
这在我的应用程序中很重要,因为我的大部分绑定都是使用 @RequestBody 完成的,如果我可以对其应用一些自定义绑定,那就太好了。
解决此问题的最常用方法是什么?并转义我的输入数据以进行脚本攻击。
【问题讨论】:
-
@InitBinder不适用于@RequestBody。与@ModelAttribute进行数据绑定时使用绑定器。@RequestBody由 Jackons 或 XML 解析器解析,或者...取决于请求的类型。如果你想要自定义绑定配置杰克逊。 -
好的,谢谢您的确认。我想我可以把
@RequestBody扔进垃圾箱,然后通过我的ajax 调用发送@ModelAttribute? -
否...
@ModelAttribute可用于绑定请求参数而不是请求正文。 -
我建议在输出数据而不是在输入时转义,因为转义方法因您输出的文档类型而异(例如,对于 html 和 csv,它是不同的)。如果您真的想在输入时使用
@ResponseBody,那么请考虑将 Jackson 配置为它。 -
@M.Deinum 我的意思是我可以删除
@RequestBody AddCommentForm form并映射类似@ModelAttribute("addCommentForm") AddCommentForm form的东西,然后我可以使用带有一些自定义映射的 initbinder。
标签: ajax spring spring-mvc spring-data