带有日期的 Java Spring RESTFull API 请求 [英] Java Spring RESTFull API Request With Dates
问题描述
我正在尝试向我创建的 api 发出请求.我必须提供名称(字符串)和日期间隔(两个日期).我收到以下错误:
I'm trying to make a request to a api that i created. I must provide a name (String) and a date interval (two Dates). I'm getting the following error:
未能将 'java.lang.String' 类型的值转换为所需类型'java.util.Date';嵌套异常是java.lang.IllegalArgumentException:无法解析日期:无法解析日期:20151211"
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "20151211"
我尝试了很多日期格式,但都没有奏效.请求 url 是这样的:
I've tried a lot of date formats, but none works. The request url is something like this:
http://localhost:8080/api/avaiableRoomTypes?hotel=Marriot&start=20151211&end=20151213
控制器方法:
@RequestMapping(value = "api/avaiableRoomTypes", method = RequestMethod.GET)
public List<Room> CheckRoomTypeAvailability(@RequestParam(value="hotel") String name,@RequestParam(value="start") Date start,@RequestParam(value="end") Date end) {
Hotel hotel = hotels.findByName(name);
Iterable<RoomType> roomtypesList = roomtypes.findByhotel(hotel);
Iterator<RoomType> roomtypesIt = roomtypesList.iterator();
List<Room> roomsList = new ArrayList<Room>();
while(roomtypesIt.hasNext()){
RoomType rt = roomtypesIt.next();
roomsList.addAll(rooms.findWithDates(start, end, rt.getId()));
}
return roomsList;
}
推荐答案
你需要在你的方法头中声明一个 String,然后在你的方法中解析 Date.
You need to declare a String in your method header, then parse the Date in your method.
您还应该注意到 Date 的字符串构造函数已被弃用 https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#Date-java.lang.String-.文档建议使用 DateFormat.好吧,假设您使用的是 Java 8.
You should also note that Date's string constructor is deprecated https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#Date-java.lang.String-. Docs suggests using DateFormat. Well, that's assuming your on java 8.
这篇关于带有日期的 Java Spring RESTFull API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!