春季-当对json使用DELETE返回错误请求

错误代码

我正在使用Spring Boot开发简单的Rest API。我通过POST方法创建用户并通过删除DELETE但是当我使用DELETEjson服务器返回时Bad Request

创建用户:

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

"OK"

获取用户:

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

[{"id":"ff80818176c9b9720176c9bdfd0c0002","name":"developer","email":"[email protected]"}]

使用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

[]

UserRepository.java

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

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

UserController.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]

我怎么了

约翰·科温

Spring @RequestParam批注

@RequestParam注释旨在从URL派生值。当您使用requestBody传递ID时,不会将其填充到deleteUser函数中。

更改方法以也使用@RequestBody批注,或者像在html查询中一样通过路径参数传递id。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章