109

我使用 Spring Boot 并包含jackson-datatype-jsr310在 Maven 中:

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

当我尝试使用带有 Java 8 日期/时间类型的 RequestParam 时,

@GetMapping("/test")
public Page<User> get(
    @RequestParam(value = "start", required = false)
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start) {
//...
}

并使用此 URL 对其进行测试:

/test?start=2016-10-8T00:00

我收到以下错误:

{
  "timestamp": 1477528408379,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
  "message": "Failed to convert value of type [java.lang.String] to required type [java.time.LocalDateTime]; 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.LocalDateTime] for value '2016-10-8T00:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-10-8T00:00]",
  "path": "/test"
}
4

13 回答 13

93

TL;DR - 您可以使用 just 将其捕获为字符串@RequestParam,或者您也可以让 Spring 通过参数另外将字符串解析为 java 日期/时间类@DateTimeFormat

@RequestParam足以在 = 符号之后获取您提供的日期,但是,它以String. 这就是它抛出强制转换异常的原因。

有几种方法可以实现这一点:

  1. 自己解析日期,将值作为字符串获取。
@GetMapping("/test")
public Page<User> get(@RequestParam(value="start", required = false) String start){

    //Create a DateTimeFormatter with your required format:
    DateTimeFormatter dateTimeFormat = 
            new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE);

    //Next parse the date from the @RequestParam, specifying the TO type as 
a TemporalQuery:
   LocalDateTime date = dateTimeFormat.parse(start, LocalDateTime::from);

    //Do the rest of your code...
}
  1. 利用 Spring 自动解析和期望日期格式的能力:
@GetMapping("/test")
public void processDateTime(@RequestParam("start") 
                            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 
                            LocalDateTime date) {
        // The rest of your code (Spring already parsed the date).
}
于 2016-10-27T04:57:26.803 回答
83

你做的一切都是正确的:)。是一个示例,可以准确显示您在做什么。只需@DateTimeFormat用.注释您的 RequestParam 无需GenericConversionService在控制器中进行特殊或手动转换。这篇博客文章对此进行了描述。

@RestController
@RequestMapping("/api/datetime/")
final class DateTimeController {

    @RequestMapping(value = "datetime", method = RequestMethod.POST)
    public void processDateTime(@RequestParam("datetime") 
                                @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateAndTime) {
        //Do stuff
    }
}

我猜你的格式有问题。在我的设置中,一切正常。

于 2017-10-02T18:14:52.587 回答
37

我在这里找到了解决方法。

Spring/Spring Boot 仅支持 BODY 参数中的日期/日期时间格式。

以下配置类在 QUERY STRING(请求参数)中添加了对日期/日期时间的支持:

// Since Spring Framwork 5.0 & Java 8+
@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        registrar.registerFormatters(registry);
    }
}

分别:

// Until Spring Framwork 4.+
@Configuration
public class DateTimeFormatConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        registrar.registerFormatters(registry);
    }
}

即使您将多个请求参数绑定到某个类,它也可以工作(@DateTimeFormat在这种情况下注释无能为力):

public class ReportRequest {
    private LocalDate from;
    private LocalDate to;

    public LocalDate getFrom() {
        return from;
    }

    public void setFrom(LocalDate from) {
        this.from = from;
    }

    public LocalDate getTo() {
        return to;
    }

    public void setTo(LocalDate to) {
        this.to = to;
    }
}

// ...

@GetMapping("/api/report")
public void getReport(ReportRequest request) {
// ...
于 2017-12-21T23:36:15.820 回答
22

就像我在评论中所说,您也可以在签名方法中使用此解决方案:@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start

于 2017-10-30T09:56:39.430 回答
11

SpringBoot 2.XX 及更新版本

如果您使用依赖spring-boot-starter-web版本2.0.0.RELEASE或更高版本,则不再需要显式包含jackson-datatype-jsr310依赖项,该依赖项已由spring-boot-starter-webthrough提供spring-boot-starter-json

这已作为 Spring Boot 问题#9297解决,并且答案 仍然有效且相关:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>
@RequestMapping(value = "datetime", method = RequestMethod.POST)
public void foo(@RequestParam("dateTime") 
                @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime ldt) {
    // IMPLEMENTATION
}
于 2020-07-02T14:30:55.480 回答
4

我遇到了同样的问题并在这里找到了我的解决方案(不使用注释)

...您必须至少在您的上下文中正确地将字符串注册到 [LocalDateTime] 转换器,以便每次您将字符串作为输入并期望 [LocalDateTime] 时,Spring 都可以使用它自动为您执行此操作。(大量的转换器已经被 Spring 实现并包含在 core.convert.support 包中,但没有一个涉及 [LocalDateTime] 转换)

所以在你的情况下,你会这样做:

public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
    public LocalDateTime convert(String source) {
        DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
        return LocalDateTime.parse(source, formatter);
    }
}

然后只需注册您的bean:

<bean class="com.mycompany.mypackage.StringToLocalDateTimeConverter"/>

带注释

将其添加到您的 ConversionService:

@Component
public class SomeAmazingConversionService extends GenericConversionService {

    public SomeAmazingConversionService() {
        addConverter(new StringToLocalDateTimeConverter());
    }

}

最后你会在你的 ConversionService 中使用@Autowire:

@Autowired
private SomeAmazingConversionService someAmazingConversionService;

您可以在此站点上阅读有关使用 spring(和格式)进行转换的更多信息。请注意,它有大量广告,但我绝对发现它是一个有用的网站,并且是对该主题的一个很好的介绍。

于 2016-12-03T23:06:38.090 回答
3

以下适用于 Spring Boot 2.1.6:

控制器

@Slf4j
@RestController
public class RequestController {

    @GetMapping
    public String test(RequestParameter param) {
        log.info("Called services with parameter: " + param);
        LocalDateTime dateTime = param.getCreated().plus(10, ChronoUnit.YEARS);
        LocalDate date = param.getCreatedDate().plus(10, ChronoUnit.YEARS);

        String result = "DATE_TIME: " + dateTime + "<br /> DATE: " + date;
        return result;
    }

    @PostMapping
    public LocalDate post(@RequestBody PostBody body) {
        log.info("Posted body: " + body);
        return body.getDate().plus(10, ChronoUnit.YEARS);
    }
}

Dto类:

@Value
public class RequestParameter {
    @DateTimeFormat(iso = DATE_TIME)
    LocalDateTime created;

    @DateTimeFormat(iso = DATE)
    LocalDate createdDate;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PostBody {
    LocalDate date;
}

测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(RequestController.class)
public class RequestControllerTest {

    @Autowired MockMvc mvc;
    @Autowired ObjectMapper mapper;

    @Test
    public void testWsCall() throws Exception {
        String pDate        = "2019-05-01";
        String pDateTime    = pDate + "T23:10:01";
        String eDateTime = "2029-05-01T23:10:01"; 

        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("")
            .param("created", pDateTime)
            .param("createdDate", pDate))
          .andExpect(status().isOk())
          .andReturn();

        String payload = result.getResponse().getContentAsString();
        assertThat(payload).contains(eDateTime);
    }

    @Test
    public void testMapper() throws Exception {
        String pDate        = "2019-05-01";
        String eDate        = "2029-05-01";
        String pDateTime    = pDate + "T23:10:01";
        String eDateTime    = eDate + "T23:10:01"; 

        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("")
            .param("created", pDateTime)
            .param("createdDate", pDate)
        )
        .andExpect(status().isOk())
        .andReturn();

        String payload = result.getResponse().getContentAsString();
        assertThat(payload).contains(eDate).contains(eDateTime);
    }


    @Test
    public void testPost() throws Exception {
        LocalDate testDate = LocalDate.of(2015, Month.JANUARY, 1);

        PostBody body = PostBody.builder().date(testDate).build();
        String request = mapper.writeValueAsString(body);

        MvcResult result = mvc.perform(MockMvcRequestBuilders.post("")
            .content(request).contentType(APPLICATION_JSON_VALUE)
        )
        .andExpect(status().isOk())
        .andReturn();

        ObjectReader reader = mapper.reader().forType(LocalDate.class);
        LocalDate payload = reader.readValue(result.getResponse().getContentAsString());
        assertThat(payload).isEqualTo(testDate.plus(10, ChronoUnit.YEARS));
    }

}
于 2019-07-12T08:29:02.007 回答
1

上面的答案对我不起作用,但我在这里犯了一个错误: https ://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring- boot/ 获胜的片段是 ControllerAdvice 注释,它的优点是可以在所有控制器上应用此修复:

@ControllerAdvice
public class LocalDateTimeControllerAdvice
{

    @InitBinder
    public void initBinder( WebDataBinder binder )
    {
        binder.registerCustomEditor( LocalDateTime.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText( String text ) throws IllegalArgumentException
            {
                LocalDateTime.parse( text, DateTimeFormatter.ISO_DATE_TIME );
            }
        } );
    }
}
于 2019-07-20T22:39:31.737 回答
1

您可以添加到配置中,此解决方案适用于可选参数和非可选参数。

@Bean
    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<>() {
            @Override
            public LocalDate parse(String text, Locale locale) {
                return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
            }

            @Override
            public String print(LocalDate object, Locale locale) {
                return DateTimeFormatter.ISO_DATE.format(object);
            }
        };
    }


    @Bean
    public Formatter<LocalDateTime> localDateTimeFormatter() {
        return new Formatter<>() {
            @Override
            public LocalDateTime parse(String text, Locale locale) {
                return LocalDateTime.parse(text, DateTimeFormatter.ISO_DATE_TIME);
            }

            @Override
            public String print(LocalDateTime object, Locale locale) {
                return DateTimeFormatter.ISO_DATE_TIME.format(object);
            }
        };
    }

于 2019-09-24T02:46:50.757 回答
1

这是另一个带有参数转换器的通用解决方案:

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import ru.diasoft.micro.msamiddleoffice.ftcaa.customerprofile.config.JacksonConfig;

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime>{

    private static final List<String> SUPPORTED_FORMATS = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "[another date time format ...]");
    private static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = SUPPORTED_FORMATS
            .stream()
            .map(DateTimeFormatter::ofPattern)
            .collect(Collectors.toList());

    @Override
    public LocalDateTime convert(String s) {

        for (DateTimeFormatter dateTimeFormatter : DATE_TIME_FORMATTERS) {
            try {
                return LocalDateTime.parse(s, dateTimeFormatter);
            } catch (DateTimeParseException ex) {
                // deliberate empty block so that all parsers run
            }
        }

        throw new DateTimeException(String.format("unable to parse (%s) supported formats are %s",
                s, String.join(", ", SUPPORTED_FORMATS)));
    }
}
于 2021-04-29T09:55:27.470 回答
0

对于全局配置:

public class LocalDateTimePropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        setValue(LocalDateTime.parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    }

}

进而

@ControllerAdvice
public class InitBinderHandler {

    @InitBinder
    public void initBinder(WebDataBinder binder) { 
        binder.registerCustomEditor(OffsetDateTime.class, new OffsetDateTimePropertyEditor());
    }

}
于 2019-12-04T03:12:19.500 回答
0

您可以在 中全局配置日期时间格式application properties。像:

spring.mvc.format.date=yyyy-MM-dd

spring.mvc.format.date-time=yyyy-MM-dd HH:mm:ss

spring.mvc.format.time=HH:mm:ss

签入mavern:org.springframework.boot:spring-boot-autoconfigure:2.5.3

于 2021-08-03T13:59:31.017 回答
0

我在相关上下文中遇到了类似的问题

我正在使用 WebRequestDataBinder 将请求参数动态映射到模型。

Object domainObject = ModelManager.getEntity(entityName).newInstance();
WebRequestDataBinder binder = new WebRequestDataBinder(domainObject);
binder.bind(request);

这段代码适用于原语,但不适用于 LocalDateTime 类型属性

为了解决这个问题,在调用 binder.bind 之前,我在调用 bind() 之前注册了一个自定义编辑器

binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport()
                {
                    @Override
                    public void setAsText(String text) throws IllegalArgumentException
                    {
                        setValue(LocalDateTime.parse(text, DateTimeFormatter.ISO_DATE_TIME));
                    }

                    @Override
                    public String getAsText() {
                        return DateTimeFormatter.ISO_DATE_TIME.format((LocalDateTime) getValue());
                    }

                }
            );

这解决了问题。

于 2022-01-29T20:07:18.743 回答