2015-03-08 74 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,你不能以正常的方式提交表單。