• springboot---->springboot中的类型转换(一)


      这里面我们简单的学习一下springboot中关于类型转换器的使用。人世间的事情莫过于此,用一个瞬间来喜欢一样东西,然后用多年的时间来慢慢拷问自己为什么会喜欢这样东西。

    springboot中的类型转换器

    我们的测试环境是springboot,一个将字符串转换成对象的例子。代码结构如下:

     

    一、实体的java类Person

    package com.linux.huhx.learn.converter;
    
    import java.io.Serializable;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 3:30
     * @Desc: 实体类
     */
    public class Person implements Serializable {
        private String username;
        private String password;
        private int age;
    
        public Person(String username, String password, int age) {
            this.username = username;
            this.password = password;
            this.age = age;
        }
    // ...get set方法
    }

    二、定义我们的将字符串转换成Person对象的转换器

    这里需要用@Component注解标识,以便被springboot纳入管理。

    package com.linux.huhx.learn.converter;
    
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 3:31
     * @Desc: 这里面的功能比较弱,主要是为了学习converter,代码不是特别的严谨。
     */
    @Component
    public class PersonConverter implements Converter<String, Person> {
    
        @Override
        public Person convert(String source) {
            if (StringUtils.isEmpty(source)) {
                return null;
            }
            System.out.println("input string: " + source);
            String[] inputParams = source.split("-");
            Person person = new Person(inputParams[0], inputParams[1], Integer.valueOf(inputParams[2]));
            return person;
        }
    }

    三、我们的测试控制器类

    package com.linux.huhx.learn.converter;
    
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 3:46
     * @Desc: 测试springboot中自定义类型转换器
     */
    
    @RestController
    @RequestMapping("/converter")
    public class PersonConverterAction {
    
        @PostMapping("/person")
        public Person convertrStringToPerson(Person person) {
            return person;
        }
    }

      通过postman发送post的请求:url为localhost:9998/converter/person。下面的截图是请求的数据,注意这里面的key=person与上述的convertrStringToPerson方法的参数名对应。

    返回数据:

    {
        "username": "linux",
        "password": "123456",
        "age": 345
    }

    控制台打印请求的参数:

    input string: linux-123456-345

    友情链接

  • 相关阅读:
    没人关注的角落是个好地方
    PICKIT3 WIN10 无法连接问题解决
    TM1650+msp430单片机 调试及遇到问题的总结
    即将会来日常更新stm32的学习过程
    Learn Arduino the hard way 1——点亮一个LED
    准备再次开始更新
    Tcl之Read files for synthesis
    Verilog之event
    Tcl之Math
    Digital design之Boolean Algebra
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootconverter1.html
Copyright © 2020-2023  润新知