温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot中如何自定义参数绑定

发布时间:2021-07-29 15:40:02 来源:亿速云 阅读:115 作者:Leah 栏目:大数据

这篇文章给大家介绍SpringBoot中如何自定义参数绑定,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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"
    
    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", "添加失败!");
}

关于SpringBoot中如何自定义参数绑定就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI