gpt4 book ai didi

java - 如何使用@putmapping编写put方法

转载 作者:行者123 更新时间:2023-12-01 17:48:31 24 4
gpt4 key购买 nike

我正在学习 Spring Rest api,并编写了以下方法将数据保存到数据库中。

@GetMapping(path="/add") // Map ONLY GET Requests
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String email) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request

User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}

现在我想编写 put 查询,它可以获取用户 ID,然后更新名称或电子邮件。另外,我需要检查用户名和电子邮件不应为空,并且电子邮件的格式是否有效。

我如何使用@putmapping构建我的方法来执行我的任务。

最佳答案

基本验证应仅在映射类中完成。

您可以引用以下示例:

假设您的映射类和请求方法如下:

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;

public class User {

@NotNull(message = "Name cannot be null")
private String name;

@Size(min = 10, max = 200, message
= "About Me must be between 10 and 200 characters")
private String aboutMe;

@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be greater than 150")
private int age;

@Email(message = "Email should be valid")
@NotNull
private String email;

// setters and getters
}

@PutMapping(path="/update")
public ResponseEntity<UserResponse> updateUser(@Valid @RequestBody User user) {
return userRepository.save(user);
}

关于java - 如何使用@putmapping编写put方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com