【问题标题】:Spring - How to map JSON form data to Controller paramaterSpring - 如何将 JSON 表单数据映射到控制器参数
【发布时间】:2015-05-09 21:44:06
【问题描述】:

我在以 JSON 格式发送表单数据并使用控制器处理它时遇到了一些问题。使用 spring 注释来解决这个问题的“最佳”方法是什么?

我希望我可以将表单数据作为对象发送到控制器,并让控制器自动将其映射到模型,但我收到错误

服务器拒绝此请求,因为请求实体的格式不受所请求方法的请求资源支持。

表格

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP JSON</title>
</head>
<body>
    <h2>Please enter name below to register</h2>
    <br>
    <h1>User Name</h1>
    <form  method="post" action="/SpringRedirecting/process/" enctype="application/json">
        <br>
        <input type="text" name="uname" value="" />
        <br>
        <input type="text" name="password" value="" />
        <br>
        <input type="submit" value="Submit" />
    </form>

</body>

控制器

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public String processRequest(@RequestBody final User user, ModelMap map, HttpServletRequest req){         
    map.addAttribute("user", user);
    return "output";   
}

【问题讨论】:

  • 您是否检查过该表单确实是作为 JSON 提交的?
  • 您好 JBNizet,我已将 enctype 设置为 JSON 是否足够?
  • 规范说:在过渡期间,不支持这种编码的用户代理将回退到使用 application/x-www-form-urlencoded。。为什么不使用浏览器控制台检查通过网络传输的内容?
  • 另外,如果您没有在 &lt;mvc:message-converters&gt; 块内配置 MappingJackson2HttpMessageConverter bean,那么 Jackson 不会用于自动将您的用户从 JSON 反序列化为对象。跨度>
  • @Jnanathan 你试过我的解决方案了吗?

标签: json spring forms model-view-controller controller


【解决方案1】:

最好的方法是拥有一个与表单数据格式相同的对象。我想您的Userunamepassword 字段,那么您的表单必须提供这两个字段。您可以执行以下操作:

$("#formId").submit(function(){
    var data = {};
    data['uname'] = $('[name="uname"]').val();
    data['password'] = $('[name="password"]').val();
    $.ajax({
    headers: {
        Accept: "application/json; charset=utf-8",
        "Content-Type": "application/json; charset=utf-8"
    },
    type: "POST",
    url: "/SpringRedirecting/process/",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    beforeSend: function(xhr) {

    },
    success: function(data) {

    },

   return false; //Prevent normal submitting of the form
});

然后你可以在你的控制器中访问data

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
    public String processRequest(@RequestBody final User user, ModelMap map, HttpServletRequest req){ 
        System.out.printLn(user.getUname());        
        //This will print the value of first input.
     } 

注意事项

  1. 您的模型必须具有 setter 和 getter。
  2. 通过 json 格式发送对象,仅适用于 ajax 请求。如果要使用json,则不能以正常方式提交表单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多