簡體   English   中英

使用 Spring 引導發布 JSON 值時出現問題

[英]Troubles posting a JSON value using Spring Boot

我正在嘗試使用 json 發出發布請求,但在 postman 中,只有當我發出這樣的請求時,請求才會成功: email@example.com 如果我使用標准 JSON 格式{"email":"email@example.com"}提出請求,我會收到“無效的 email id”。 我應該提到,在 postman 中檢查了內容類型application/json header,並且我在 body/raw 中提出請求。

我曾嘗試使用consumes = "application/json"弄亂@RequestBody / @RequestParam注釋,但我沒有成功,而且經過大量谷歌搜索后我也找不到類似的問題。

我的 controller:

@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注解將HttpRequest body映射到一個傳輸或域object。你需要把object而不是String

您的端點應該如下所示。

@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      
}

你應該有 Email model 和字符串屬性email

public EmailPayload {

  String email;
.....

然后它將起作用(它將適合您提供的 json)。 Ofcouse class name can be different, only thing that must match is email property, then in your Controller your @RequestBody will be this class, and not String you have now.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM