Jquery ajaxの投稿データを@RequestBodyとしてSpringコントローラに苦労しています。Spring ControllerとJquery AjaxはJson文字列をObjectに変換できません
私はJSON文字列を送信し、コントローラでJSON文字列を取得できました。しかし、JSON Stringをjquery ajaxからコントローラー[オブジェクトとして変換できません]に送信できません。それはいつも言っている
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.3</version>
</dependency>
::私はポンポンで同様ジャクソン依存性を持っている
<c:if test='${not empty ajitems}'>
var responseObject = JSON.stringify('${ajitems}');
</c:if>
// ${ajitems}--> is the model attribute and setting it in javascript to //send it back to controller through ajax call
//Controller:
@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json") **//unable to convert to requestBody**
public String testAjaxPost(@RequestBody AjaxDto[] ajaxRes, Model model,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(ajaxRes);
return "ajaxform";
}
:
**Ajax Call:**
function postLoad(){
$.ajax({
type : 'POST',
url : "ajaxhai.do",
contentType : "application/json",
cache : false,
data : responseObject, **//json-String**
dataType :"html",
success : function(data, textStatus) {
console.log("POST success");
$("#ajaxContent").html(data);
},
error : function(request, status, error) {
console.log("failed" + error);
}
});
}
// responseObjectが初期化:以下
は、コードスニペットですjquery-3.2.1.min.js:4 POST http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 400 (Bad Request)
しかし、私は次のようにコントローラを変更すると、魅力のように働いている:私はここに欠けているということです
@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json")**//Please note : here it is String and not Object[]**
public String testAjaxPost(@RequestBody String ajaxRes, Model model,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(ajaxRes);
Gson gson = new Gson();
TestAjaxDto[] mcArray = gson.fromJson(ajaxRes, TestAjaxDto[].class);
List<TestAjaxDto> mcList = new ArrayList<TestAjaxDto>(Arrays.asList(mcArray));
System.out.println(mcList);
return "ajaxform";
}
何?私はまだ自動json変換のためのすべての可能性を試したことがない幸運。
何か助けていただければ幸いです。
ありがとうございます。
ajaxリクエストでdataTypeをhtmlと記述しました。私はそれが 'application/json'であるべきか、単にそれを削除するべきだと思います。 –
@VijendraKulhade dataTypeは、期待される戻り値の型を意味します。私は試してみましたが、依然として応答は同じです/*RequestURL:http://localhost:8080/testSpringmvc-1.0/ajaxhai.do リクエスト方法:POST ステータスコード:400 Bad Request リモートアドレス:[: :1]:8080 */ – venkatVJ
私はdataTypeとcontentTypeと混同しています。 –