我正在使用java spring mvc和angular js。
我创建了一个休息服务:
@RestController
public class UserApiController {
@Autowired
private UserService userService;
@RequestMapping(value = "/users/createUser", method = RequestMethod.POST)
public @ResponseBody void addUser(@RequestBody UserRequestDTO newUser) {
userService.addUser(newUser);
}
我的角度控制器是这样的:
var newUser = { surname : "orozco", name: "daniel", password: "pepe", email:"dani@dani.com" };
$http.post(getCompletePath("users/createUser"), JSON.stringify(newUser))
.success(function () {
alert("ok");
}).error(function () {
});
我的UserRequestDTO
public class UserRequestDTO {
private String email;
private String password;
private String name;
private String surname;
+ getters and setters
它返回以下错误:415(不支持的媒体类型)。
如果我发送一个没有参数的字符串,它就可以了。所以,问题在于参数
答案 0 :(得分:0)
我不知道AngularJS,但尝试在AngularJS代码中添加Content-Type。它应该看起来像这样(根据规范https://docs.angularjs.org/api/ng/service/ $ http):
var newUser = {
surname : "orozco",
name: "daniel",
password: "pepe",
email:"dani@dani.com" };
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {'Content-Type': 'application/json'},
data: newUser};
$http(req)
.success(function () {alert("ok");})
.error(function () {});
答案 1 :(得分:0)
这可能是因为Content-Type标头,请尝试明确包含它 如下,
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {
'Content-Type': 'application/json'
},
data: {surname : "orozco", name: "daniel", password: "pepe", email:"dani@dani.com" },
}
$http(req).success(function(){...}).error(function(){...});
答案 2 :(得分:0)
我忘了在pom.xml中包含org.codehaus.jackson。它解决了问题