這是我在 慕課網(wǎng) 觀看 SpringMVC 數(shù)據(jù)綁定入門 所做的學(xué)習(xí)筆記
其中包含對 **List,Set,Map,JSON,XML 的數(shù)據(jù)綁定以及 PropertyEditor辅肾、Formatter教翩、Converter 三種自定義類型轉(zhuǎn)換器 **
-
List 類型綁定
-
特點(diǎn)
- List 對象綁定需要建立一個(gè) List 集合包裝類
public class User { private int age; private String name; // 省略 setter getter } public class ListUserWrap { private List<User> userList; // 省略 setter getter }
- List 的長度為前臺傳入的 ** 集合最大下標(biāo)加 1**
@ResponseBody @RequestMapping(value = "/list2") public String list2(ListUserWrap listUserWrap) { return "listUserWrapSize:" + listUserWrap.getUserList().size() + "\tlistUserWrap:" + listUserWrap; }
-
測試數(shù)據(jù)
http://localhost/list2?userList[0].name=a&userList[1].name=b
listUserWrapSize:2 listUserWrap:ListUserWrap(userList=[User(age=0, name=a), User(age=0, name=b)])
http://localhost/list2?userList[0].name=a&userList[1].name=b&userList[3].name=c
listUserWrapSize:4 listUserWrap:ListUserWrap(userList=[User(age=0, name=a), User(age=0, name=b), User(age=0, name=null), User(age=0, name=c)])
-
-
Set 類型綁定
-
特點(diǎn)
- Set 對象綁定需要建立一個(gè) Set 集合包裝類
- 需要先定義 Set 集合長度, 并且前臺傳過來的 Set 長度不能越界, 否者報(bào)錯(cuò)
- ** 設(shè)置 Set 長度時(shí)需要注意重寫對象的 hashCode,equals 方法, 否者后面的會掩蓋前面的 **
public class SetUserWrap { private Set<User> userSet; // 省略 setter getter public SetUserWrap() { userSet = new LinkedHashSet<>(); userSet.add(new User()); User user = new User(); user.setName("b"); userSet.add(user); } }
-
測試數(shù)據(jù)
http://localhost/set?userSet[0].name=a 因?yàn)轭A(yù)先定義的第二個(gè)對象的 name 為 b, 所以此處返回 b
setUserWrapSize:2 setUserWrap:SetUserWrap(userSet=[User(age=0, name=a), User(age=0, name=b)])
http://localhost/set?userSet[0].name=a&userSet[1].name=bbb
setUserWrapSize:2 setUserWrap:SetUserWrap(userSet=[User(age=0, name=a), User(age=0, name=bbb)])
-
-
Map 類型綁定
-
特點(diǎn)
- 建立一個(gè) Map 包裝類
public class MapUserWrap { private Map<String, User> userMap; // 省略 setter getter } @ResponseBody @RequestMapping(value = "/map") public String map(MapUserWrap mapUserWrap) { return "mapUserWrapSize:" + mapUserWrap.getUserMap().size() + "\tmapUserWrap:" + mapUserWrap; }
-
測試數(shù)據(jù)
http://localhost/map?userMap["a"].name=a&userMap["b"].name=b
mapUserWrapSize:2 mapUserWrap:MapUserWrap(userMap={a=User(age=0, name=a), b=User(age=0, name=b)})
http://localhost/map?userMap["a"].name=a&userMap["a"].name=b
mapUserWrapSize:1 mapUserWrap:MapUserWrap(userMap={a=User(age=0, name=a,b)})
-
-
JSON 類型綁定
- 前臺在 body 區(qū)域傳入以下類型格式字符串
{ "name":"a", "age":1 }
@ResponseBody @RequestMapping(value = "/json") public String json(@RequestBody User user) { return user.toString(); }
-
XML 類型綁定
- 前臺在 body 區(qū)域傳入以下類型格式字符串
<xmluser> <name>a</name> <age>1</age> </xmluser>
- 建立一個(gè) XML 包裝類
@XmlRootElement(name = "xmluser")// 根節(jié)點(diǎn)標(biāo)簽名 public class XmlUser { @XmlElement(name = "name")// 屬性標(biāo)簽名 private String name; @XmlElement(name = "age")// 屬性標(biāo)簽名 private int age; }
@ResponseBody @RequestMapping(value = "/xml") public String xml(@RequestBody XmlUser xmlUser) { return xmlUser.toString(); }
-
自定義類型轉(zhuǎn)換 - PropertyEditor
在 Controller 中編寫一個(gè)帶有 InitBinder 注解的方法, 傳入 WebDataBinder 對象, 使用該對象注冊指定類型的轉(zhuǎn)換關(guān)系, 對該方法所在 Controller 中使用該類型的方法參數(shù)有效
@ResponseBody @RequestMapping(value = "/date") public String date(Date date) { return date.toLocaleString(); } @ResponseBody @RequestMapping(value = "/date2") public String date2(Date date2) { return date2.toLocaleString(); } @InitBinder("date")// 指定對變量名為 date 進(jìn)行轉(zhuǎn)換, 不會對 date2 生效 private void initDate(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); //binder.registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) //new CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) //allowEmpty 是否允許 Date 對象為空 }
-
自定義類型轉(zhuǎn)換 - Formatter
根據(jù)
String
類型自定義轉(zhuǎn)換規(guī)則轉(zhuǎn)換成需要的類型, 需要實(shí)現(xiàn)org.springframework.format.Formatter<T>
接口,T
為想要轉(zhuǎn)換的結(jié)果類型- 創(chuàng)建自定義 Formatter
public class DateFormatter implements Formatter<Date> { @Override public Date parse(String text, Locale locale) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = dateFormat.parse(text); } catch (ParseException e) { e.printStackTrace(); } return date; } @Override public String print(Date object, Locale locale) { return null; } }
- 將自定義的 Formatter 注入到 SpringMVC 默認(rèn)的 FormattingConversionServiceFactoryBean 中, 同時(shí)將默認(rèn)轉(zhuǎn)換規(guī)則服務(wù)類配置為已經(jīng)被注入的 bean 對象
<mvc:annotation-driven conversion-service="myFormattingConversionService"/> <bean id="myFormattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters">,<!-- 此處為 formatters--> <set> <bean class="{包路徑}.DateFormatter"></bean> </set> </property> </bean>
-
自定義類型轉(zhuǎn)換 - Converter
自己指定數(shù)據(jù)來源類型及轉(zhuǎn)換結(jié)果類型, 相比 Formatter 更為靈活, 需要實(shí)現(xiàn)
org.springframework.core.convert.converter.Converter<S, T>
接口,S
為來源類型,T
為結(jié)果類型- 創(chuàng)建自定義 Converter
public class DateConverter implements Converter<String, Date> { @Override public Date convert(String source) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = dateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } return date; } }
- 將自定義的 Converter 注入到 SpringMVC 默認(rèn)的 FormattingConversionServiceFactoryBean 中, 同時(shí)將默認(rèn)轉(zhuǎn)換規(guī)則服務(wù)類配置為已經(jīng)被注入的 bean 對象
<mvc:annotation-driven conversion-service="myFormattingConversionService"/> <bean id="myFormattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"><!-- 此處為 converters--> <set> <bean class="{包路徑}.DateConverter"></bean> </set> </property> </bean>