SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)
功能區(qū)別:
兩者的作用一樣,都是類型轉(zhuǎn)換。
- org.springframework.format.Formatter只能做String類型到其他類型的轉(zhuǎn)換。
- org.springframework.core.convert.converter.Converter可以做任意類型的轉(zhuǎn)換。
Converter是一般工具,可以將一種類型轉(zhuǎn)換成另一種類型。例如,將String轉(zhuǎn)換成Date,或者將Long轉(zhuǎn)換成Date。Converter既可以用在web層,也可以用在其它層中。Formatter只能將String轉(zhuǎn)成成另一種java類型。例如,將String轉(zhuǎn)換成Date,但它不能將Long轉(zhuǎn)換成Date。
Formatter
Formatter使用示例:
1.定義Formatter類:
需要實(shí)現(xiàn)Formatter接口, 并在pase方法中進(jìn)行轉(zhuǎn)換的邏輯。通過(guò)@Component自動(dòng)將其添加到SpringBoot容器,這樣就會(huì)自動(dòng)生效。
@Component public class StudentFormatter implements Formatter<Student> { /** * 校驗(yàn)不太嚴(yán)密,僅作演示 */ @Override public Student parse(String text, Locale locale) { if (NumberUtils.isParsable(text)) { Student s = new Student(); s.setAge(Integer.parseInt(text)); return s; } return null; } @Override public String print(Student money, Locale locale) { if (money == null) { return null; } return money.getAge()+""; } }
2.Controller中的代碼:
@PostMapping(path = "/stu") @ResponseBody public String sst(NewRequest newCoffee) { return newCoffee.getStudent().getAge()+""; }
數(shù)據(jù)實(shí)體:
@Getter @Setter @ToString public class NewRequest { private String name; private Student student; }
3.訪問(wèn):http://localhost:8080/stu
采用application/x-www-form-urlencoded 參數(shù)類型傳遞參數(shù)。
這樣服務(wù)端收到參數(shù),就會(huì)自動(dòng)將字符串轉(zhuǎn)換成一個(gè)Student對(duì)象。
注意點(diǎn):這里采用了application/x-www-form-urlencoded提交參數(shù),所以在Controller中不能加@RequestBody,并且參數(shù)名稱要和數(shù)據(jù)對(duì)象的屬性保持一致。如果采用json格式數(shù)據(jù)交互,測(cè)試發(fā)現(xiàn)解析報(bào)錯(cuò)。
{ "timestamp": "2019-09-05T07:42:00.809+0000", "status": 400, "error": "Bad Request", "message": "JSON parse error: Current token (VALUE_STRING) not numeric, can not use numeric value accessors; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors\n at [Source: (PushbackInputStream); line: 1, column: 29] (through reference chain: geektime.spring.springbucks.waiter.controller.request.NewCoffeeRequest[\"price\"])", "path": "/coffee/addJson" }
說(shuō)明在轉(zhuǎn)換成自定義的對(duì)象時(shí),必須通過(guò)form格式進(jìn)行傳參。
但奇怪的是Date類型的轉(zhuǎn)換,通過(guò)json格式傳遞參數(shù),可以正常轉(zhuǎn)換。 如下:
@Component public class DateFormatter implements Formatter<Date> { @Override public Date parse(String text, Locale locale) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); System.out.println("parse input text: " + text); System.out.println("parse date: " + dateFormat.parse(text)); return dateFormat.parse(text); } @Override public String print(Date object, Locale locale) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); System.out.println("print method." + object); return dateFormat.format(object); } }
Controller中:
@ResponseBody @PostMapping(path = "/date") public String formatterStringToDate(@RequestBody ZXRequest date) { System.out.println("action method: " + date.getDate().getTime()); return date.getDate().getTime()+""; }
數(shù)據(jù)類:
@Getter @Setter @ToString public class ZXRequest { private Date date; }
訪問(wèn):
可以正常返回。說(shuō)明轉(zhuǎn)換正確。關(guān)于原因,目前尚不清楚,有知道的,希望留言。
Converter使用示例:
1.創(chuàng)建轉(zhuǎn)換類:其他步驟和Formatter完全一樣。
@Component public class StudentConvert implements Converter<String ,Student> { @Override public Student convert(String text) { if (NumberUtils.isParsable(text)) { Student s = new Student(); s.setAge(Integer.parseInt(text)); return s; } return new Student(); } }
如果同時(shí)定義了Converter和Formatter,并且轉(zhuǎn)換同一個(gè)類型,會(huì)采用哪個(gè)進(jìn)行轉(zhuǎn)換?
測(cè)試證明,同時(shí)定義Student的轉(zhuǎn)換類,會(huì)采用Formatter。
到此這篇關(guān)于SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)SpringBoot Formatter Converter 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)HTTP請(qǐng)求的4種方式總結(jié)
這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)HTTP請(qǐng)求的4種方式,在java開發(fā)中,經(jīng)常遇到需要調(diào)用第三方提供的接口服務(wù)的需求,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下2023-08-08SpringBoot整合Kafka完成生產(chǎn)消費(fèi)的方案
網(wǎng)上找了很多管理kafka整合springboot的教程,但是很多都沒(méi)辦法應(yīng)用到生產(chǎn)環(huán)境,很多配置都是缺少,或者不正確的,只能當(dāng)個(gè)demo,所以本文給大家介紹了SpringBoot整合Kafka完成生產(chǎn)消費(fèi)的方案,需要的朋友可以參考下2024-12-12Java rmi遠(yuǎn)程方法調(diào)用基本用法解析
這篇文章主要介紹了Java rmi遠(yuǎn)程方法調(diào)用基本用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05Java 序列化詳解及簡(jiǎn)單實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了 Java 序列化詳解及簡(jiǎn)單實(shí)現(xiàn)實(shí)例的相關(guān)資料,使用序列化目的:以某種存儲(chǔ)形式使自定義對(duì)象持久化,將對(duì)象從一個(gè)地方傳遞到另一個(gè)地方,需要的朋友可以參考下2017-03-03微信公眾號(hào)獲取access_token的方法實(shí)例分析
這篇文章主要介紹了微信公眾號(hào)獲取access_token的方法,結(jié)合實(shí)例形式分析了java實(shí)現(xiàn)微信公眾號(hào)獲取access_token的相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2019-10-10