且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有请求内容类型表单的 Http Post 在 Spring MVC 3 中不起作用

更新时间:2022-06-01 05:25:11

不幸的是 FormHttpMessageConverter(当内容类型为 时用于 @RequestBody 注释的参数application/x-www-form-urlencoded) 不能绑定目标类(如 @ModelAttribute 可以).

Unfortunately FormHttpMessageConverter (which is used for @RequestBody-annotated parameters when content type is application/x-www-form-urlencoded) cannot bind target classes (as @ModelAttribute can).

因此您需要 @ModelAttribute 而不是 @RequestBody.如果您不需要将不同的内容类型传递给该方法,您可以简单地替换注释:

Therefore you need @ModelAttribute instead of @RequestBody. If you don't need to pass different content types to that method you can simply replace the annotation:

@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@ModelAttribute UserAccountBean account) { ... }

否则我猜你可以创建一个单独的方法表单处理具有适当的headers 属性的表单数据:

Otherwise I guess you can create a separate method form processing form data with the appropriate headers attribute:

@RequestMapping(method = RequestMethod.POST, 
    headers = "content-type=application/x-www-form-urlencoded") 
public ModelAndView createFromForm(@ModelAttribute UserAccountBean account) { ... }

另一种可能的选择是通过组合 FormHttpMessageConverter(将输入消息转换为参数映射)和WebDataBinder(将参数映射转换为目标对象).

Another possible option is to implement your own HttpMessageConverter by combining FormHttpMessageConverter (to convert input message to the map of parameters) and WebDataBinder (to convert map of parameters to the target object).