gpt4 book ai didi

java - 当我用户 Angular 发布数据时,我在 Spring Controller 中得到空值

转载 作者:行者123 更新时间:2023-12-01 21:40:10 25 4
gpt4 key购买 nike

我使用 Angularjs 将数据发送到 spring Controller 。

像这样。

var user ={
"userID" : "1",
"username" : "hello",
"password" : "123456"
};
console.log(user);
var response = $http.post("/login/signup",user);
response.success(function (data) {
alert("success");
alert(data);
});
response.error(function (data) {
alert("error");
alert(data);
});

我的模型

public class User {
private long userID;
private String username;
private String password;

public User(){

}

public User(long userID, String username, String password) {
this.userID = userID;
this.username = username;
this.password = password;
}


public long getUserID() {
return userID;
}

public void setUserID(long userID) {
this.userID = userID;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

还有我的 Controller 。

@Controller
@RequestMapping(value = "/login")
public class LoginController {

@RequestMapping(value = "/signup",method = RequestMethod.POST)
public String signUp(User user){
String username = user.getUsername();// NULL!!
System.out.println(username);
return "login";
}

}

我得到这样的空用户。

如果我将 @RequestBody 添加到我的 Controller 。我什至无法进入 Controller 并出现异常。

@RequestMapping(value = "/signup",method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_VALUE})
public String signUp(@RequestBody User user){
String username = user.getUsername();
System.out.println(username);
return "login";
}

异常

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

最佳答案

当您将数据发布到服务器时,您可能需要在请求 header 中设置 Content-Type: application/json

还可以使用:

@RequestMapping(value = "/signup",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)

安装:

@RequestMapping(value = "/signup",method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_VALUE})

编辑

有时(我不确定什么时候),MappingJackson2HttpMessageConverter 不会向负责将请求参数转换为模型 bean 的 spring 上下文注册。如果未注册,手动注册可能会解决问题。

关于java - 当我用户 Angular 发布数据时,我在 Spring Controller 中得到空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com