[英]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.