zoukankan      html  css  js  c++  java
  • 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

    友情链接

  • 相关阅读:
    sqlserver-一次updlock和withnolock和with check option 的报错原因分析
    类库文件引用web服务报错解决方法-在 ServiceModel 客户端配置部分中,找不到引用协定的默认终结点元素
    用timer自定义计划任务时间
    console 程序随系统启动及隐藏当前程序窗口
    爱积多合作农场正式上线试运营
    CSS-三列布局
    CSS-垂直居中
    form表单重置
    CSS3 选择器
    Tab选项卡
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootconverter1.html
Copyright © 2011-2022 走看看