ロブ:
私はjQueryのから春RestControllerにJSONパッケージを送信するとき、私は多くのエラーを持っています:
春に:
解決[org.springframework.web.HttpMediaTypeNotSupportedException:コンテンツタイプ 'アプリケーション/ JSON;のcharset = UTF-8' サポートされていません]
Chromeで:
POST のhttp:// localhost /をポスト 415
(匿名)@ main.js:11
私のjQueryのコード:
$(document).ready(function() {
$('#go').on('click', function() {
var user = {
"name" : "Tom",
"age" : 23
};
$.ajax({
type: 'POST',
url: "http://localhost/post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(user),
dataType: 'json',
async: true
});
});
});
私の春RestControllerコード:
@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
System.out.println("-------------------------");
return new User("Tom", 56); //'Get' Check
}
}
エンティティユーザー:
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
}
Code_Mode:
あなたはすなわちMEDIATYPE間違っを使用しているAPPLICATION_FORM_URLENCODED_VALUE
残りconttrollerに消費するため。使用MediaType.APPLICATION_JSON_UTF8_VALUE
あなたがJSONリクエストを渡しているよう。
@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
System.out.println("-------------------------");
return new User("Tom", 56); //'Get' Check
}
}