springboot类型转换
由于springMVC不支持前端传递的日期格式自动转换为java8的日期类型。
三种解决方案:
1、使用String接收
使用String接收之后,在后端手动转换,比较麻烦
2、使用自定义类型转换器
实现Converter接口
import java.time.LocalDate;
import org.springframework.core.convert.converter.Converter;
import com.study.testSpringBoot.converter.utils.DateUtilsJava8;
/**
* 重写Spring入参类型转换器
* string——date
*
*/
public class ToLocalDate implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String date) {
return DateUtilsJava8.getStringToLocalDate(date);
}
}
import java.time.LocalDateTime;
import org.springframework.core.convert.converter.Converter;
import com.study.testSpringBoot.converter.utils.DateUtilsJava8;
/**
* 重写Spring入参类型转换器
* string——date
*
*/
public class ToLocalDateTime implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String date) {
return DateUtilsJava8.getStringToDateTime1(date);
}
}
写一个配置类,实现WebMvcConfigurer接口中的addFormatters方法
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ToLocalDate());
registry.addConverter(new ToLocalDateTime());
}
}
在controller层中使用,可以自动转换
@PostMapping("/testDate")
public String testDate(TestVo test) {
System.out.println("dateTime:"+test.getDate1()+"date:" + test.getDate2());
return "success";
}
3、使用@InitBinder注解
在controller中使用@InitBinder注解也可以实现自动转换,但是这样写的话每个controller中都要实现,有冗余,可以在一个BaseController中实现这个方法,然后其他controller继承BaseController
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.study.testSpringBoot.converter.utils.DateUtilsJava8;
@RestController
public class TestController {
/**
* 将前台传递过来的日期格式的字符串,自动转化为java8日期类型
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtilsJava8.getStringToLocalDate(text));
}
});
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtilsJava8.getStringToDateTime1(text));
}
});
}
@PostMapping("/testDate")
public String testDate(TestVo test) {
System.out.println("dateTime:"+test.getDate1()+"date:" + test.getDate2());
return "success";
}
}