springboot之类型转换器-日期转换器

版本:springboot.2.1.6.RELEASE
1、pom依赖
pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.linst</groupId>
    <artifactId>paramconverter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>paramconverter</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、创建一个日期转换器
MyDateConverter:

package cn.linst.paramconverter;

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

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


@Component
public class MyDateConverter implements Converter<String,Date> {
    
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @Override
    public Date convert(String source) {
    
    
        if (source != null && !"".equals(source)) {
    
    
            try {
    
    
                return sdf.parse(source);
            } catch (ParseException e) {
    
    
                e.printStackTrace();
            }
        }
        return null;
    }
}

3、创建一个控制器
HelloController:

package cn.linst.paramconverter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


@RestController
public class HelloController {
    
    
    @GetMapping("/hello")
    public void hello(Date date) {
    
    
        System.out.println(date);
    }
}

4、运行,请求地址:

http://localhost:8080/hello?date=2021/03/30

控制台打印:

Tue Mar 30 00:00:00 CST 2021

猜你喜欢

转载自blog.csdn.net/tongwudi5093/article/details/115338750