SpringBoot中自定义参数绑定

本文是vhr系列的第十篇,vhr项目地址https://github.com/lenve/vhr

正常情况下,前端传递来的参数都能直接被SpringMVC接收,但是也会遇到一些特殊情况,比如Date对象,当我的前端传来的一个日期时,就需要服务端自定义参数绑定,将前端的日期进行转换。自定义参数绑定也很简单,分两个步骤:

1.自定义参数转换器

自定义参数转换器实现Converter接口,如下:

public class DateConverter implements Converter<String,Date> {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    public Date convert(String s) {
        if ("".equals(s) || s == null) {
            return null;
        }
        try {
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
 

convert方法接收一个字符串参数,这个参数就是前端传来的日期字符串,这个字符串满足yyyy-MM-dd格式,然后通过SimpleDateFormat将这个字符串转为一个Date对象返回即可。

2.配置转换器

自定义WebMvcConfig继承WebMvcConfigurerAdapter,在addFormatters方法中进行配置:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }
}
 
 

OK,如上两步之后,我们就可以在服务端接收一个前端传来的字符串日期并将之转为Java中的Date对象了,前端日期控件如下:

<el-date-picker
    v-model="emp.birthday"
    size="mini"
    value-format="yyyy-MM-dd HH:mm:ss"
    style="width: 150px"
    type="date"
    placeholder="出生日期">
</el-date-picker>
 
 

服务端接口如下:

@RequestMapping(value = "/emp", method = RequestMethod.POST)
public RespBean addEmp(Employee employee) {
    if (empService.addEmp(employee) == 1) {
        return new RespBean("success", "添加成功!");
    }
    return new RespBean("error", "添加失败!");
}
 
 

其中Employee中有一个名为birthday的属性,该属性的数据类型是一个Date,源码我就不贴了,小伙伴直接在本项目源码中查看即可。

本系列其他文章:

1.SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(一)
2.SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(二)
3.SpringSecurity中密码加盐与SpringBoot中异常统一处理
4.axios请求封装和异常统一处理
5.权限管理模块中动态加载Vue组件
6.SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(六)
7.vhr部门管理数据库设计与编程
8.使用MyBatis轻松实现递归查询与存储过程调用
9.ElementUI中tree控件踩坑记

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值