在使用SpingMVC框架的項(xiàng)目中,經(jīng)常會(huì)遇到頁(yè)面某些數(shù)據(jù)類型是Date、Integer、Double等的數(shù)據(jù)要綁定到控制器的實(shí)體,或者控制器需要接受這些數(shù)據(jù),如果這類數(shù)據(jù)類型不做處理的話將無(wú)法綁定。
這里我們可以使用注解@InitBinder來(lái)解決這些問(wèn)題,這樣SpingMVC在綁定表單之前,都會(huì)先注冊(cè)這些編輯器。一般會(huì)將這些方法些在BaseController中,需要進(jìn)行這類轉(zhuǎn)換的控制器只需繼承BaseController即可。其實(shí)Spring提供了很多的實(shí)現(xiàn)類,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是夠用的。
demo如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
public class BaseController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date. class , new MyDateEditor()); binder.registerCustomEditor(Double. class , new DoubleEditor()); binder.registerCustomEditor(Integer. class , new IntegerEditor()); } private class MyDateEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); Date date = null ; try { date = format.parse(text); } catch (ParseException e) { format = new SimpleDateFormat( "yyyy-MM-dd" ); try { date = format.parse(text); } catch (ParseException e1) { } } setValue(date); } } public class DoubleEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals( "" )) { text = "0" ; } setValue(Double.parseDouble(text)); } @Override public String getAsText() { return getValue().toString(); } } public class IntegerEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals( "" )) { text = "0" ; } setValue(Integer.parseInt(text)); } @Override public String getAsText() { return getValue().toString(); } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/heyonggang/p/6186633.html