SpringBoot自定義請求參數轉換器


需求

我們可能對接客戶的系統的時候,雖然Spring為我們提供的很多方便的轉換器,但是遇到還是可能遇到需要自定義請求參數轉換器的情況。

日期轉換器

SpringBoot默認是沒有配置日期轉換器的我們可以自己寫,也可以使用配置讓SpringBoot來生成:https://www.jianshu.com/p/4b29beffcd8e

日期轉換器配置代碼:

package com.wzq.config.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: 字符串轉換為DateConverter
 * @author: Wzq
 * @create: 2020-01-17 16:33
 */
@Component
public class StringToDateConverter implements Converter<String, Date> {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String s) {
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }
}

自定義轉換器

package com.wzq.config.converter;


import com.wzq.test.model.UserModel;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

/**
 * @description: 字符串轉UserModel類
 * @author: Wzq
 * @create: 2020-01-17 16:24
 */
@Component
public class StringToUserModelConverter implements Converter<String, UserModel>{

    @Override
    public UserModel convert(String s) {
        String[] split = s.split("-");
        String userName = split[0];
        Integer age = Integer.parseInt(split[1]);
        UserModel userModel = new UserModel();
        userModel.setUserName(userName);
        userModel.setAge(age);
        return userModel;
    }
}

UserModel實體類

package com.wzq.test.model;

import lombok.Data;

import java.util.Date;

/**
 * @description:
 * @author: Wzq
 * @create: 2020-01-17 15:17
 */
@Data
public class UserModel {
    private String userName;
    private Integer age;
    private Date date;
}

請求地址

http://192.168.0.115:8080/myproject/test/noAnnotationsMethod?userName=GosingWu&age=18&date=2012-12-12

成功:
image.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM