2015-03-08 73 views
1

我在将表单数据作为JSON发送并使用控制器进行处理时遇到了一些问题。使用Spring注释来解决这个问题的“最佳”方式是什么?春季 - 如何将JSON表单数据映射到控制器参数

我的希望是,我可以在表单数据发送到控制器作为对象,并有控制其映射到自动模式,但IM接收到错误

服务器拒绝这个请求,因为请求实体的格式不是请求的资源所支持的格式。

形式

<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"; 
} 
+0

您是否检查过表单确实以JSON格式提交? – 2015-03-08 18:22:25

+0

嗨JBNizet,我已经设置为JSON这种足够的enctype? – Jnanathan 2015-03-08 18:41:33

+1

规范说:*在过渡期间,不支持此编码的用户代理将回退到使用application/x-www-form-urlencoded。*。你为什么不使用浏览器控制台检查网络上发生了什么? – 2015-03-08 19:16:06

回答

0

,最好的办法是有一个与您的表单数据格式相同的对象。我想你的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. 你的模型必须有getter和setter方法。
  2. 通过json格式发送对象,仅适用于ajax请求。如果你想使用json,你不能以正常的方式提交表单。