有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring在将DELETE与json一起使用时返回错误请求

我正在用spring boot开发简单的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

[]

用户存储库。爪哇

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

用户服务。爪哇

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

用户控制器。爪哇

@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]

我怎么了


共 (1) 个答案

  1. # 1 楼答案

    Spring @RequestParam Annotation

    @RequestParam注释旨在从URL派生值。当您通过requestBody传入id时,它不会被填充到deleteUser函数中

    或者将该方法更改为同时使用@RequestBody注释,或者像在html查询中一样通过path参数传入id