我是 spring 新手,在创建一个 POSTMapping 来 addUser 时,我在邮递员上收到 406 错误,在控制器类中收到 null 。
package com.codedecode.userinfo.DTO;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
private int userId;
private String userName;
private String userPassword;
private String address;
private String city;
}
下面是我发送到控制器的 JSON
{
"userName": "John",
"userPassword": "password123",
"address": "123 Main St",
"city": "Anytown"
}
实体类在下面
package com.codedecode.userinfo.Entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.*;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String userName;
private String userPassword;
private String address;
private String city;
}
下面是映射界面。
package com.codedecode.userinfo.mapper;
import com.codedecode.userinfo.DTO.UserDTO;
import com.codedecode.userinfo.Entity.User;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
@Mapper
public interface UserMapper {
@Autowired
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
UserDTO mapUserToUserDTO(User user);
User mapUserDTOtoUser(UserDTO userDTO);
}
这是控制器类代码
@PostMapping("/addUser")
public ResponseEntity<UserDTO> addUser(@RequestBody UserDTO userDTO){
UserDTO savedUser = userService.addUser(userDTO);
return new ResponseEntity<>(savedUser, HttpStatus.OK);
}
我得到了 userDTO 对象,但用户名,用户密码一切都是空的
看来您的项目或 IDE 中的 lombok 配置有问题。要检查 UserDto 映射器接口实现是否已正确生成,如果不是这种情况,我会推荐您这篇post。此外,请确保您在 IDE 中启用了注释处理器。这可以解决你的问题