【问题标题】:How to pass Date as Parameter from controller to API?如何将日期作为参数从控制器传递到 API?
【发布时间】:2019-06-24 09:56:59
【问题描述】:

我有控制器:-

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

我想将日期从控制器传递到 API。每当我尝试将日期从控制器传递到 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]

我无法理解,即使在将 Date 添加到 MultivalueMap 的 Date 类型之后,API 是如何将 Date 视为 String 类型的?

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

【问题讨论】:

  • 嗨@Nikant,我假设这个API可以通过其他调用工作,考虑到你不能改变对吧?

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


【解决方案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 将其格式化为日期的唯一方法。

【讨论】:

  • 嘿,Avi,如果你看一下他的例子 .. 他没有在 RequestParam 中传递日期,而是在正文中传递。
  • 嘿@Brother,您可以将表单数据作为Map 传递,resttemplate 会将其视为查询参数,因此@RequestMapping 逻辑将起作用。如果你看postForObject(源码),具体来说doWithRequest(ClientHttpRequest httpRequest)这个方法负责判断请求是Body还是FormData,所以当你没有传递一个正确的Class或者Object 这将被视为 FormData 并将写为 Param。这个魔法是由FormHttpMessageConverter 完成的。调查一下
  • 酷,我问他是不是真的不能改变..因为他在描述中说他不能改变api。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多