1

我已经创建了一个 Jhipster 应用程序,yo jhipster并使用yo jhipster:entity hikelist.

当我尝试使用 jhipster 生成的服务和控制器来保存我的实体时,我收到了 BAD REQUEST 400。我找不到此错误的原因。未调用 java 资源。有没有办法在我的 http 请求中获取有关此问题原因的更多信息?

我的后端资源:

@RequestMapping(value = "/rest/hikelists",
    method = RequestMethod.POST,
    produces = "application/json")
@Timed
public void create(@RequestBody HikelistDTO hikelist) {
    log.debug("REST request to save Hikelist : {}", hikelist);
    hikelistRepository.save(hikelist);
}

在客户端使用 http 调用的 create 函数:

$scope.create = function () {
Hikelist.save($scope.hikelist,
  function () {
    $scope.hikelists = Hikelist.query();
    $('#saveHikelistModal').modal('hide');
    $scope.clear();
  });
};

我错过了什么?还有什么要配置的吗?

谢谢你。

4

1 回答 1

2

问题是您的 JSON 没有正确序列化到您的 DTO 中,很可能是因为您不想手动触摸的 ID 或其他一些值,而是希望您的数据库管理。我刚刚遇到了同样的问题,并找到了一个不错的、干净的解决方法,根本不改变 Angular:

  1. 向 DTO 添加两个新方法,以便可以从 JSON 字符串或 null 实例化它:

    public UserDTO(String firstName, String lastName, String email, Map<String, Boolean> roles) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.roles = roles;
    }
    

    public static UserDTO fromJsonToUserDTO(String json) {
        return new JSONDeserializer<UserDTO>()
        .use(null, UserDTO.class).deserialize(json);
    }
    
  2. 更新您的服务以接受 JSON 结构而不是直接 DTO,然后仅使用您想要的字段转换为内联 DTO。

    @RequestMapping(value = "/rest/account",
            method = RequestMethod.POST,
            produces = "application/json")
    @Timed
    public void saveAccountFromJSON(@RequestBody String json) throws IOException {
        UserDTO userDTO = UserDTO.fromJsonToUserDTO(json);
        userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
    }
    
于 2014-04-05T23:24:21.337 回答