【问题标题】:How to write a put method with @putmapping如何使用 @putmapping 编写 put 方法
【发布时间】:2019-03-18 03:35:53
【问题描述】:

我正在学习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 构建我的方法来执行我的任务。

【问题讨论】:

  • 这方面的文章应该很多,你google一下吗?
  • 我试过但我不明白。好吧,我会再试一次
  • 你真的应该深入学习一些广泛的教程。实际上,在代码 sn-p 中唯一看起来没问题的是方法的名称。首先,您将使用 POST 而不是 PUT 来添加新用户。其次,您可以接收整个用户对象而不是参数。第三,验证不在控制器中进行,而是在使用 BeanValidation 的实体上或在服务层中进行。第四,你的问题不够具体,所以我要投票结束它。请不要气馁。学习构建 Spring Restful Apps 不是一天完成的。
  • “我想写 put 查询” 提示: PUT 不是一个查询。跨度>

标签: java spring rest spring-boot


【解决方案1】:

基本验证只能在映射类中完成。

你可以参考下面的例子:

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

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);
}

【讨论】:

    【解决方案2】:

    你可以按照你的建议去做,但我只是传递整个要更新的对象:

    @PutMapping(path="/update")
    public @ResponseBody String updateUser(@RequestBody User user) {
        userRepository.save(user);
        return "Updated"; }
    

    对于空检查字段和验证电子邮件,您可以有一个 validateUserFields 函数,该函数接受一个用户对象并返回一个布尔值,以便您可以:

    if(validateUserFields(user)) 
        userRepository.save(user)
    

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2019-09-23
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多