java - 值在 java spring Controller 中使用 post 方法接收 null

标签 java json spring rest spring-boot

我尝试通过 postman 使用 post 方法对我的 spring boot 应用程序进行 API 调用。 这是输入:

{
  "username": "name",
  "password": "1234",
  "age": 12,
  "salary": 5000,
  "role": 1
}

Controller 中的代码如下:

@RequestMapping(value = "/signup", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> saveUser(@RequestBody UserDto user) {
        try {
            System.out.println(user.getUsername()); // => name
            System.out.println(user.getPassword()); // => 1234
            System.out.println(user.getSalary()); // => 5000
            System.out.println(user.getRoleDto()); // => null
            System.out.println(user.getAge()); // => 24
            userService.save(user);
            return ResponseEntity.ok().body("insert done");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

user.getRoleDto() 外,所有属性都打印它们的值,它始终为 null。但是,当我尝试在 Controller 中使用它(代码下方)时,它会像输入对象一样打印整个对象。

@RequestMapping(value="/signup", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> saveUser(HttpEntity<String> httpEntity){
    try {
        String json = httpEntity.getBody();
        System.out.println(json);
        return ResponseEntity.ok().body("insert done");
    } catch (Exception e) {
        return ResponseEntity.badRequest().body(e.getMessage());
    }
}

这是我的 User.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@Column
@JsonIgnore
private String password;
@Column
private long salary;
@Column
private int age;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "role_id")
private Role role;
// getters and setters

这是我的 Role.java

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "role_name", nullable = false)
private String roleName;
// getters and setters

这是我的 UserDto.java

private String username;
private String password;
private int age;
private long salary;
private RoleDto roleDto;

这是我的 RoleDto.java

private Long id;
private String roleName;

这里出了什么问题?任何帮助都会非常有帮助。谢谢!

更新

感谢 Burm87,我从他的答案建议中选择了选项 1。但是,不知何故,spring 仍然将 role_id 视为 null,甚至现在打印了该值。这是在 userServiceImpl 中:

    @Override
    public User save(UserDto user) throws Exception {
        User newUser = new User();
        BeanUtils.copyProperties(user, newUser, "password");
        // above line is refer to [here][1].
        newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
        try {
            userDao.save(newUser);
        } catch (Exception e) {
            throw new Exception(e);
            // this throw "Column role_id cannot be null"
        }
        return newUser;
    }

但是,如果我使用下面的代码,setRole 方法不适用,因为我在 DTO 中将 user.getRole() 定义为int 但将 User 实体中的 newUser.setRole() 定义为 Role。但是,如果我将 User 实体中的 setRole 更改为 int,那么,我如何告诉 spring 关于 ManyToOne UserRole 之间的关系?注意:我想我只是想将 role 的输入参数设为上面提供的 integer

@Override
public User save(UserDto user) throws Exception {
    User newUser = new User();
    newUser.setUsername(user.getUsername());
    newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
    newUser.setAge(user.getAge());
    newUser.setSalary(user.getSalary());
    newUser.setRole(user.getRole()); // here is the problem
    try {
        userDao.save(newUser);
    } catch (Exception e) {
        throw new Exception(e);
    }
    return newUser;
}

最佳答案

这里有两个选择:

1) 您保留您的请求并将 DTO 中的此字段 roleDto 更改为名为 role 的整数字段(相应地重命名 getter 和 setter);

2) 你保持你的 DTO 不变,你改变你的请求发送:

{
  "username": "name",
  "password": "1234",
  "age": 12,
  "salary": 5000,
  "roleDto": {
      "id": 1,
      "roleName": "your role name"
  }
}

关于java - 值在 java spring Controller 中使用 post 方法接收 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730896/

相关文章:

java - 线程 "main"java.lang.IllegalArgumentException : n must be positive 中的异常

java - 为什么在装饰器中调用安全认证属性 `principal.displayName`会抛出异常?

java - 如何在内存不足错误时进行线程转储

c++ - 使用 yaml-cpp 解析 json/yaml 数组

javascript - AngularJS - 使用结果从 Factory 读取 JSON

javascript - SyntaxError : JSON. 解析:JavaScript 中 JSON 数据第 1 行第 92 列的 JSON 数据后出现意外的非空白字符

java - 在同一功能中将用户从一种布局重定向到另一种布局 - java thymeleaf spring

java - 扩展抽象类时出现 Spring BeanDefinitionStoreException

java - 使用 Class 作为 HashMap 的键是否会导致不良影响?

java - 为什么我的程序在获取字符串而不是字符时会自行终止?