【问题标题】:Troubles posting a JSON value using Spring Boot使用 Spring Boot 发布 JSON 值的问题
【发布时间】:2020-09-22 03:39:54
【问题描述】:

我正在尝试使用 json 进行发布请求,但在邮递员中,只有当我发出这样的请求时,请求才会成功:email@example.com。如果我使用标准 JSON 格式 {"email":"email@example.com"} 发出请求,我会收到“无效的电子邮件 ID”。我应该提一下,在邮递员中检查了内容类型application/json 标头,并且我在 body/raw 中发出请求。

我曾尝试使用consumes = "application/json" 弄乱@RequestBody/@RequestParam 注释,但我没有成功,而且经过大量谷歌搜索后我也找不到类似的问题。

我的控制器:

@RestController
public class UserController {

@Autowired
private UserService userService;

@PostMapping(value = "/forgot-password", consumes = "application/json")
public String forgotPassword(@RequestBody String email) {

    String response = userService.forgotPassword(email);

    if (!response.startsWith("Invalid")) {
        response = "http://localhost:8080/reset-password?token=" + response;
    }
    return response;
}

用户服务:

public String forgotPassword(String email) {

    Optional<User> userOptional = Optional
            .ofNullable(userRepository.findByEmail(email));

    if (!userOptional.isPresent()) {
        return "Invalid email id.";
    }

    User user = userOptional.get();
    user.setToken(generateToken());
    user.setTokenCreationDate(LocalDateTime.now());

    user = userRepository.save(user);

    return user.getToken();
}

【问题讨论】:

  • 您说@RequestBody 应该是String不是会映射到具有email 属性的对象。

标签: java json spring rest postman


【解决方案1】:

简单地说,@RequestBody 注解将 HttpRequest 主体映射到传输或域对象。您需要放置对象而不是字符串

您的端点应该如下所示。

@PostMapping(value = "/forgot-password", consumes = "application/json")
public String forgotPassword(@RequestBody EmailDto email) {

    String response = userService.forgotPassword(email.getEmail);
    // ...
    return response;
}

您的 DTO 应如下所示

public class EmailDto {

    private String email; 
    //Getters and Setters      
}

【讨论】:

  • 我收到一个错误,因为我在电子邮件类中没有@id 注释,我应该把什么作为 id?电子邮件类只是“用户”表的一列,它没有自己的 id...
【解决方案2】:

您应该拥有带有字符串属性email 的电子邮件模型。

public EmailPayload {

  String email;
.....

然后它将起作用(它将适合您提供的 json)。 Ofcouse 类名可以不同,唯一必须匹配的是 email 属性,然后在你的控制器中你的 @RequestBody 将是这个类,而不是你现在拥有的 String

【讨论】:

    猜你喜欢
    • 2019-03-01
    • 2017-11-04
    • 2019-10-01
    • 2016-07-02
    • 2023-02-24
    • 2017-06-28
    • 2017-10-15
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多