spring-when use delete with json返回错误请求

tzxcd3kk  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(423)

我正在用springboot开发简单的restapi。我通过 POST 方法。并通过 DELETE . 但当我使用 DELETE 使用json服务器返回 Bad Request .
正在创建用户:

ubuntu@ubuntu-pc:~$ curl -X POST -H "Content-type: application/json" -d '{"name": "developer", "email": "dev@mail.com"}' http://localhost:8080/add-user

"OK"

获取用户:

ubuntu@ubuntu-pc:~$ curl  http://localhost:8080

[{"id":"ff80818176c9b9720176c9bdfd0c0002","name":"developer","email":"dev@mail.com"}]

使用json删除用户:

ubuntu@ubuntu-pc:~$ curl -X DELETE -H "Content-type: application/json" -d '{"id": "ff80818176c9b9720176c9bdfd0c0002"}' http://localhost:8080/del-id

{"timestamp":"2021-01-03T19:47:15.433+00:00","status":400,"error":"Bad Request","message":"","path":"/del-id"}

使用html查询删除用户:

ubuntu@ubuntu-pc:~$ curl -X DELETE  http://localhost:8080/del-id?id=ff80818176c9b9720176c9bdfd0c0002

"OK"

ubuntu@ubuntu-pc:~$ curl  http://localhost:8080

[]

用户存储库.java

public interface UserRepository extends CrudRepository<UserRecord, String> {
}

用户服务.java

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<UserRecord> getAllUsers() {
        List<UserRecord> userRecords = new ArrayList<>();
        userRepository.findAll().forEach(userRecords::add);

        return userRecords;
    }

    public void addUser(UserRecord user) {
        userRepository.save(user);
    }

    public void deleteUser(String id) {
        userRepository.deleteById(id);
    }
}

用户控制器.java

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public List<UserRecord> getAllUser() {
        return userService.getAllUsers();
    }

    @RequestMapping(value="/add-user", method=RequestMethod.POST)
    public HttpStatus addUser(@RequestBody UserRecord userRecord) {
        userService.addUser(userRecord);

        return HttpStatus.OK;
    }

    @RequestMapping(value="/del-id", method=RequestMethod.DELETE)
    public HttpStatus deleteUser(@RequestParam("id") String id) {
        userService.deleteUser(id);

        return HttpStatus.OK;
    }
}

jvm日志:

2021-01-03 22:47:15.429  WARN 30785 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'id' is not present]

我怎么了?

bihw5rsg

bihw5rsg1#

spring@requestparam注解
@requestparam注解设计用于从url派生值。当您通过requestbody传入id时,它不会被填充到deleteuser函数中。
要么将方法更改为同时使用@requestbody注解,要么像在html查询中那样通过path param传入id。

相关问题