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
友情链接
- 一个比较好的converter和formatter的学习博客:https://segmentfault.com/a/1190000005708254
作者:
huhx
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。