天天看點

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控件踩坑記

繼續閱讀