我需要找到一个日期范围之间的条目,并想在Spring Boot API中进行GET调用,如下所示
$ curl -X GET http://localhost:8080/api/v1/appointments/findWithRange?start=2018-10-01&end=2018-10-15
我写了GET调用
@GetMapping("/findWithRange")
public ResponseEntity<List<Appointment>> findAllWithCreationRange(@RequestParam("start") Date start, @RequestParam("end") Date end) {
List<Appointment> appointments = service.findAllWithCreationRange(start, end);
if (Objects.isNull(appointments)) {
ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(appointments);
}
我得到了回复,
{"timestamp":"2019-02-10T07:58:22.151+0000","status":400,"error":"Bad Request","message":"Required Date parameter 'end' is not present","path":"/api/v1/appointments/findWithRange"}
如何正确编写呼叫?似乎我无法调试,因为断点无法捕获。
答案 0 :(得分:3)
您的问题很简单-在通话中
$ curl -X GET http://localhost:8080/api/v1/appointments/findWithRange?start=2018-10-01&end=2018-10-15
&
符号告诉操作系统'在后台运行curl -X GET http://localhost:8080/api/v1/appointments/findWithRange?start=2018-10-01
'。这就是end
日期不确定的原因。
只需用双引号括住您的URL:
$ curl -X GET "http://localhost:8080/api/v1/appointments/findWithRange?start=2018-10-01&end=2018-10-15"
答案 1 :(得分:1)
如果要接收参数作为日期,则需要定义模式。 试试这个:
@GetMapping("/findWithRange")
public ResponseEntity<List<Appointment>> findAllWithCreationRange(@RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd") Date start, @RequestParam("end") @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
List<Appointment> appointments = service.findAllWithCreationRange(start, end);
if (Objects.isNull(appointments)) {
ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(appointments);
}
如果要接收sql.Date,则需要使用自定义反序列化器。试试这个:
@GetMapping("/findWithRange")
public ResponseEntity<List<Appointment>> findAllWithCreationRange(@RequestParam("start") @JsonDeserialize(using = SqlDateConverter.class) Date start, @RequestParam("end") @JsonDeserialize(using = SqlDateConverter.class) Date end) {
List<Appointment> appointments = service.findAllWithCreationRange(start, end);
if (Objects.isNull(appointments)) {
ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(appointments);
}
SQL日期转换器:
public class SqlDateConverter extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return Date.valueOf(p.getText());
}
}
如果要全局反序列化sql.Date,请尝试仅添加此bean:
@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Date.class,new SqlDateConverter());
objectMapper.registerModule(module);
builder.configure(objectMapper);
return builder;
}
答案 2 :(得分:1)
您应指定@DateTimeFormat
Here,您可以找到更多详细信息