java 具有空构造函数的Sping Boot 防止在Postman POST请求中阅读正文

cbwuti44  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(89)

我正在学习一个spring-boot教程,我试图创建一个方法来将新用户添加到用户列表中(目前),我注意到在“User”类中有一个空的构造函数会阻止spring-boot从请求体中获取值,
我用一个原始的JSON体对http://localhost:8080/users做了一个 Postman 请求
删除带有空构造函数的行似乎可以解决这个问题。我不明白为什么。
为什么删除空构造函数就能解决这个问题?我错过了什么
我有点新的Spring任何帮助将不胜感激,谢谢!
User类:

public class User {

    private int Id;
    private String Name;
    private String Email;
    private String Password;

    public User() {} //deleting this seems so solve issue

    public User(int id, String name, String email, String password) {
        Id = id;
        Name = name;
        Email = email;
        Password = password;
    }

    public int getId() {
        return Id;
    }

    public String getName() {
        return Name;
    }

    public String getEmail() {
        return Email;
    }

    public String getPassword() {
        return Password;
    }
}

UserService类:

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService {

    List<User> users =new ArrayList<>( Arrays.asList(
            new User(1, "ff", "1", "1"),
            new User(2, "qqq", "qq", "qqq")
    ));

    public List<User> GetAllUsers() {
        return users;
    }

    public User getUser(int id) {
        return users.stream()
                .filter(x -> x.getId() == id)
                .findFirst()
                .orElse(null);
    }

    public void addUser(User user) {
        users.add(user);
    }
}

用户控制器类:

@Autowired
    private UserService userService;

    @RequestMapping("/users")
    public List<User> getAllUsers(){
        return userService.GetAllUsers();
    }

    @RequestMapping("users/{id}")
    public User getUser(@PathVariable int id){
        return userService.getUser(id);
    }

    @RequestMapping(method = RequestMethod.POST,value = "/users")
    public void addUser(@RequestBody User user){
        userService.addUser(user);
    }

}
类的main方法:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TodoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TodoApplication.class, args);
    }
    
}
erhoui1w

erhoui1w1#

Alex K这种奇怪行为的真实的原因是Jackson如何使用你的getter/setter来序列化对象,它的预期成员变量以小写字母开头在你的情况下你的变量以大写字母开头,导致这种奇怪的行为,如果你的成员变量不遵循java约定,那么它会导致奇怪的行为,因为Jackson希望你的变量遵循它

public class User {

    private int Id;  // change them to lowercase id
    private String Name;
    private String Email;
    private String Password;

    /*private int id;
    private String name;
    private String email;
    private String password;*/

更多信息请参阅此--https://stackoverflow.com/a/75884462/16769477

相关问题