如何使用 Jersey REST 客户端在 REST URL 中传递 java.util.date

How to pass java.util.date in REST urls using Jersey REST cleint

在我的 Java Spring MVC 网络应用程序中,我使用 Jersey REST 客户端。我试图通过向服务器发送两个 Date 对象来获取一些数据。但是我无法在 url 中使用 Date 对象。恐怕如果我将它们转换为字符串,我可能无法在我的服务器端获得准确的时间戳。我的 url 将是:

RESTDomain/siteid/{siteid}/pickupdate/{pickupdate}/returndate/{returndate}/pickuplocation/{pickuplocation}/returnlocation/{returnlocation}

所以有了数据,它看起来像:

/siteid/5/pickupdate/Thu Apr 14 00:00:00 IST 2016/returndate/Fri Apr 29 00:01:00 IST 2016/pickuplocation/1/returnlocation/1

我的控制器是:

@ResponseBody
@RequestMapping(
  value = "/siteid/{siteid}/pickupdate/{pickupdate}/returndate/{returndate}/pickuplocation/{pickuplocation}/returnlocation/{returnlocation}",
  method = RequestMethod.GET,
  headers = "Accept=application/json"
)
public CarDetailsListHB getDetails(
  @ModelAttribute("siteid") int siteId,
  @ModelAttribute("pickuplocation") int pickUpLocation,
  @ModelAttribute("returndate") Date returnDate,
  @ModelAttribute("pickupdate") Date pickupDate, 
  @ModelAttribute("returnlocation") int returnLocation,
  ModelMap model
) {
  //logic here
}

有什么解决办法吗?任何帮助,将不胜感激。谢谢

您可以将其作为字符串传递并转换为所需的 format.Below 代码采用与传递的字符串相同格式的字符串和 returns java.util.Date。 检查以下内容:

//your date as String
String date="Thu Apr 14 00:00:00 IST 2016";
            SimpleDateFormat dateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
            Date returnDate=dateformat.parse(date);//returnDate will have the Date object in same format.
            System.out.println(returnDate);

你的@ModelAttribute("returndate") String returnDate应该是字符串类型。 在你的控制器方法中

SimpleDateFormat dateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
                Date newReturnDate=dateformat.parse(returnDate);//newReturnDate will have the Date object in same format.

要修改时间部分,您可以尝试以下方法:

Calendar cal = Calendar.getInstance();
            cal.setTime(newReturnDate);

            cal.set(Calendar.HOUR,11 );
            cal.set(Calendar.MINUTE,39 );   
            newReturnDate=cal.getTime();
            System.out.println(newReturnDate);

因此 newReturnDate 将更新 time.You 需要从您的字符串“11:39”中获取 int 值(小时和分钟部分)。