如何将日期作为参数从控制器传递到API?

时间:2019-06-24 09:56:59

标签: spring-boot spring-mvc spring-restcontroller spring-rest

我有控制器:-

@RequestMapping(value = "/360ScoreCard", method = RequestMethod.POST)
public @ResponseBody Object get360ScoreCard(@RequestParam("userEmail") String userEmail,
        @RequestParam("valid_from") String from, @RequestParam("valid_till") String till) throws ParseException {

    if (userEmail != null) {
        String uri = util.getRestApiHost() + "userScoreFor360" + "?userEmail=" + userEmail;

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date valid_from = (Date) formatter.parse(from);
        Date valid_till = (Date) formatter.parse(till);

        MultiValueMap<String, Date> paramMap = new LinkedMultiValueMap<String, Date>();
        paramMap.add("valid_from", valid_from);
        paramMap.add("valid_till", valid_till);

        RestTemplate restTemplate = new RestTemplate();
        Response response = restTemplate.postForObject(uri, paramMap, Response.class);
        return response;
    }
    return "User Email is Null";
}

我有API:-

    @RequestMapping(value = "/userScoreFor360", method = RequestMethod.POST)
public Object getScoreFor360( @RequestParam String userEmail,Date valid_from, Date valid_till, HttpServletResponse initResponse) {
    logger.debug("Enter into method getScoreFor360()");
    Response response=new Response();
    JSONObject obj = new JSONObject();
    try {
        response = scoreService.get360Score(userEmail,valid_from,valid_till);
        Feedback360 fbThreeSixty = (Feedback360) response.getResult();
        List<ThreeSixtyRatings> listOfRating = fbThreeSixty.getRating_list();
        JSONArray jsonArray = new JSONArray();
        for (ThreeSixtyRatings ratings : listOfRating) {
            JSONObject json = new JSONObject();
            json.put("category", ratings.getCategory());
            json.put("rating_average", ratings.getRating_average());
            json.put("number_feedbacks", ratings.getNumber_feedbacks());
            jsonArray.put(json);
        }
        obj.put("rating_list", jsonArray);
        obj.put("aggregate", fbThreeSixty.getAggregate());
    } catch (Exception e) {
        logger.error("Exception in userScoreFor360 Mobile Api :", e);
    } 
    logger.debug("Exit from method getScoreFor360()" + new Gson().toJson(response));
    return obj.toString();
}

我想将日期从Controller传递到API。每当我尝试将Date从控制器传递给API时,都会引发异常:-

2019-06-24 15:15:34.437  WARN 2672 --- [nio-8180-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '1516300200000'; nested exception is java.lang.IllegalArgumentException]

我无法理解,即使在将Dates添加到MultivalueMap的Date类型的位置之后,API如何将Date视为字符串类型?

请注意:-我无法更改API。

1 个答案:

答案 0 :(得分:-1)

您已经错过了@RequestParam,但是如果您需要以Date消费,也可以

@RequestMapping(value = "/userScoreFor360", method = RequestMethod.POST)
public Object getScoreFor360( @RequestParam String userEmail, 
                              @RequestParam @DateTimeFormat(pattern="yyyy-MM-dd") Date valid_from,
                              @RequestParam @DateTimeFormat(pattern="yyyy-MM-dd") Date valid_till, 
                              HttpServletResponse initResponse) {

    //LOGIC

    return obj.toString();
}

或者是将valid_from和valid_to用作String并使用SimpleDateFormat将其格式化为最新格式的唯一方法。