gpt4 book ai didi

java - 如何让 Spring MVC 读取日期格式为 "2019-3-29"的路径参数?

转载 作者:行者123 更新时间:2023-12-02 09:46:42 24 4
gpt4 key购买 nike

我想获取一个作为查询参数传递给 Spring MVC Controller 的日期。

我有这样的依赖:

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

我的网址如下所示:

http://localhost:8080/userProducts/2?date=2019-3-29

我的 Controller 类如下所示:

package trainingapp.userproduct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import trainingapp.calculations.NutrientsCalculationFacade;
import trainingapp.historysystemofmeals.HistorySystemService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
public class UserProductController {

private final NutrientsCalculationFacade userProductCalculationFacade;
private final UserProductFindOperationService userProductFindOperationService;
private final HistorySystemService historySystemService;

@Autowired
public UserProductController(NutrientsCalculationFacade userProductCalculationFacade, UserProductFindOperationService userProductFindOperationService, HistorySystemService historySystemService) {
this.userProductCalculationFacade = userProductCalculationFacade;
this.userProductFindOperationService = userProductFindOperationService;
this.historySystemService = historySystemService;
}

//yyyy-MM-dd
@GetMapping("/userProducts/{userID}")
public String getAllEatenSummedNutrientsByGivenIDInParticularDay(@PathVariable int userID,
@RequestParam("date")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
return historySystemService.getAllEatenSummedNutrientsByGivenIDInParticularDay(userID, date);
}
}

我收到以下错误:

{
"timestamp": "2019-03-29T15:22:44.640+0000",
"status": 400,
"error": "Bad Request",
"message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value '2019-3-29'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2019-3-29]",
"path": "/userProducts/2"
}

我应该更改或添加什么?我试图用 How to use LocalDateTime RequestParam in Spring? I get "Failed to convert String to LocalDateTime" 解决这个问题,但没有成功。

最佳答案

2019-3-29 是一个错误的输入400 状态代码是准确的。请参阅DateTimeFormat.ISO#DATE文档:

The most common ISO Date Format yyyy-MM-dd, e.g. "2000-10-31".

因此,为了匹配上述格式,您的输入应改为 2019-03-29

关于java - 如何让 Spring MVC 读取日期格式为 "2019-3-29"的路径参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com