springboot接口接收前端字符串类型日期 及 接口返回格式化日期

接口接收字符串日期

接口接收参数是日期(Date)类型,但是前端传递的是字符串日期(2019-11-11);

这时调用接口会报错:

XXX Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property XXX

解决:

在对应的参数上注解:@DateTimeFormat

    /**
     * 考核结束日期
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date perfEndTm;

这样接口就可以接收字符串类型日期啦。

接口格式化日期返回

增加注解  @JsonFormat(,pattern = "yyyy-MM-dd HH:mm:ss")

@JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss")
private Date inGateTime;

 

好的,假设我们有一个枚举类`ColorEnum`表示颜色: ```java public enum ColorEnum { RED("红色"), GREEN("绿色"), BLUE("蓝色"); private String description; ColorEnum(String description) { this.description = description; } public String getDescription() { return description; } } ``` 我们现在需要在Spring Boot的Controller中接收一个枚举类型字符串参数,然后将其转换为相应的枚举类型。可以使用Spring Boot提供的`@RequestParam`注解和`org.springframework.core.convert.converter.Converter`接口来实现: ```java @RestController @RequestMapping("/colors") public class ColorController { @GetMapping public String getColor(@RequestParam("color") ColorEnum color) { return "你选择的颜色是:" + color.getDescription(); } @Component public static class ColorEnumConverter implements Converter<String, ColorEnum> { @Override public ColorEnum convert(String source) { try { return ColorEnum.valueOf(source.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("无效的颜色值:" + source); } } } } ``` 在上面的例子中,我们定义了一个`ColorEnumConverter`类实现了`Converter`接口,并在其中实现了将字符串转换为枚举类型的逻辑。然后我们将它标记为`@Component`,以便让Spring Boot自动将它注册为一个转换器。在`getColor`方法中,我们直接将`@RequestParam`注解的参数类型设置为`ColorEnum`,Spring Boot会自动根据参数类型使用我们定义的转换器将字符串转换为枚举类型
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值