SpringMVC數(shù)據(jù)綁定流程之?dāng)?shù)據(jù)轉(zhuǎn)換

SpringMVC數(shù)據(jù)綁定流程

SpringMVC主框架將ServletRequest對(duì)象及處理方法入?yún)?duì)象實(shí)例傳遞給DataBinder,DataBinder調(diào)用裝配在SpringMVC上下文中的ConversionService組件進(jìn)行數(shù)據(jù)類(lèi)型轉(zhuǎn)換,數(shù)據(jù)格式化的工作,將ServletRequest中的消息填充到入?yún)?duì)象中,然后再調(diào)用Validator組件對(duì)已綁定了請(qǐng)求消息數(shù)據(jù)的入?yún)?duì)象進(jìn)行數(shù)據(jù)合法性檢驗(yàn)叭披,并最終生成數(shù)據(jù)綁定結(jié)果BindingResult對(duì)象熏纯,BindingResult包含了已完成數(shù)據(jù)綁定的入?yún)?duì)象掐场,還包含相應(yīng)的校驗(yàn)錯(cuò)誤對(duì)象嚷堡。

數(shù)據(jù)綁定

自定義數(shù)據(jù)轉(zhuǎn)換

修改配置及核心類(lèi)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    <context:component-scan base-package="converter"/>
    <!-- 自定義參數(shù)綁定 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!-- 轉(zhuǎn)換器 -->
        <property name="converters">
            <set>
                <!-- StringToUser -->
                <bean class="converter.StringToStudentConverter"/>
            </set>
        </property>
    </bean>
</beans>

@Data
public class Student implements Serializable {
    private static final long serialVersionUID = -3244941439014026595L;
    private String name;
    private String realName;
}


public class CustomDateConverter implements Converter<String,Date> {
    public Date convert(String s) {
        //實(shí)現(xiàn) 將日期串轉(zhuǎn)成日期類(lèi)型(格式是yyyy-MM-dd HH:mm:ss)

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            //轉(zhuǎn)成直接返回
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //如果參數(shù)綁定失敗返回null
        return null;

    }
}

@Controller
public class StudentController {
    @RequestMapping("/student")
    public String save(@RequestParam("student") Student student) {
        System.out.println(student);
        return "success";
    }
}  

在瀏覽器輸入:http://localhost:8080/spring/student?student=wjk:snail

源碼走讀

從DispatcherServlet類(lèi)的doDispatch()調(diào)用handle開(kāi)始追代碼
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());


//AbstractNamedValueMethodArgumentResolver
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    Class<?> paramType = parameter.getParameterType();
    NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);

    Object arg = resolveName(namedValueInfo.name, parameter, webRequest);
    if (arg == null) {
        if (namedValueInfo.defaultValue != null) {
            arg = resolveDefaultValue(namedValueInfo.defaultValue);
        }
        else if (namedValueInfo.required) {
            handleMissingValue(namedValueInfo.name, parameter);
        }
        arg = handleNullValue(namedValueInfo.name, arg, paramType);
    }
    else if ("".equals(arg) && (namedValueInfo.defaultValue != null)) {
        arg = resolveDefaultValue(namedValueInfo.defaultValue);
    }
    //初始化DataBinder
    if (binderFactory != null) {
        WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
        arg = binder.convertIfNecessary(arg, paramType, parameter);
    }

    handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);

    return arg;
}
//DefaultDataBinderFactory
public final WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName)
        throws Exception {
    WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest);
    if (this.initializer != null) {
        this.initializer.initBinder(dataBinder, webRequest);
    }
    initBinder(dataBinder, webRequest);
    return dataBinder;
}
//ConfigurableWebBindingInitializer
public void initBinder(WebDataBinder binder, WebRequest request) {
    binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
    if (this.directFieldAccess) {
        binder.initDirectFieldAccess();
    }
    if (this.messageCodesResolver != null) {
        binder.setMessageCodesResolver(this.messageCodesResolver);
    }
    if (this.bindingErrorProcessor != null) {
        binder.setBindingErrorProcessor(this.bindingErrorProcessor);
    }
    //綁定validator
    if (this.validator != null && binder.getTarget() != null &&
            this.validator.supports(binder.getTarget().getClass())) {
        binder.setValidator(this.validator);
    }
    //綁定conversionService
    if (this.conversionService != null) {
        binder.setConversionService(this.conversionService);
    }
    if (this.propertyEditorRegistrars != null) {
        for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
            propertyEditorRegistrar.registerCustomEditors(binder);
        }
    }
}

接下來(lái)的代碼便是具體的轉(zhuǎn)化處理,有興趣可以自行閱讀。

@InitBinder裝配自定義編輯器

修改配置及核心類(lèi)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="conversion.way3"/>
</beans>


public class CustomStudentEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text.indexOf(":") > 0) {
            Student user = new Student();
            user.setName("wangjingkun");
            setValue(user);
        } else {
            throw new IllegalArgumentException("dept param is error");
        }

    }
}

@Controller
public class StudentController {
    //裝配自定義編輯器
    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Student.class,new CustomStudentEditor());
    }

    @RequestMapping("/student")
    public String save(@RequestParam("student") Student student) {
        System.out.println(student);
        return "success";
    }
} 

@WebBindingInitializer裝配自定義編輯器

修改配置及核心類(lèi)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 注冊(cè)到適配器中 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="conversion.way2.MyBindingInitializer"></bean>
        </property>
    </bean>

    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="conversion.way2"/>
</beans>

public class MyBindingInitializer implements WebBindingInitializer {
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
         binder.registerCustomEditor(Student.class,new CustomStudentEditor());
    }
}

@Controller
public class StudentController {
    @RequestMapping("/student")
    public String save(@RequestParam("student") Student student) {
        System.out.println(student);
        return "success";
    }
}  

如果對(duì)同一個(gè)類(lèi)型對(duì)象來(lái)說(shuō)同時(shí)裝配了自定義轉(zhuǎn)化器和自定義編輯器則優(yōu)先順序:

@InitBinder定義的編輯器優(yōu)先,其次conversionService定義的轉(zhuǎn)換器,最后是@WebBindingInitializer定義的編輯器。

Java原生的數(shù)據(jù)編輯器的不足

  1. 只支持字符串和Java對(duì)象之間的轉(zhuǎn)換,不支持兩個(gè)Java類(lèi)型之間的轉(zhuǎn)換。

  2. 對(duì)注解不明感,不能實(shí)施高級(jí)轉(zhuǎn)換邏輯。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末唐全,一起剝皮案震驚了整個(gè)濱河市延届,隨后出現(xiàn)的幾起案子械念,更是在濱河造成了極大的恐慌希停,老刑警劉巖棍潘,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件肴楷,死亡現(xiàn)場(chǎng)離奇詭異呵恢,居然都是意外死亡鳄橘,警方通過(guò)查閱死者的電腦和手機(jī)鲸湃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)晒衩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)掉瞳,“玉大人该镣,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)背传,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮瞳购,結(jié)果婚禮上变丧,老公的妹妹穿的比我還像新娘。我一直安慰自己萧芙,他們只是感情好运吓,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布站欺。 她就那樣靜靜地躺著,像睡著了一般地粪。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,274評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音凭疮,去河邊找鬼纲酗。 笑死,一個(gè)胖子當(dāng)著我的面吹牛莫鸭,可吹牛的內(nèi)容都是我干的卿拴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼苏研,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了大渤?” 一聲冷哼從身側(cè)響起切黔,我...
    開(kāi)封第一講書(shū)人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤孩哑,失蹤者是張志新(化名)和其女友劉穎抚垄,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡呆馁,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年桐经,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片浙滤。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡阴挣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瓷叫,到底是詐尸還是另有隱情屯吊,我是刑警寧澤,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布摹菠,位于F島的核電站盒卸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏次氨。R本人自食惡果不足惜蔽介,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望煮寡。 院中可真熱鬧虹蓄,春花似錦、人聲如沸幸撕。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)坐儿。三九已至律胀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間貌矿,已是汗流浹背炭菌。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留逛漫,地道東北人黑低。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像酌毡,于是被迫代替她去往敵國(guó)和親克握。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理枷踏,服務(wù)發(fā)現(xiàn)玛荞,斷路器,智...
    卡卡羅2017閱讀 134,654評(píng)論 18 139
  • 目錄 前言 屬性編輯器介紹 重要接口和類(lèi)介紹 源碼分析 編寫(xiě)自定義的屬性編輯器 總結(jié) 參考資料 前言 Spring...
    yang2yang閱讀 1,544評(píng)論 0 5
  • 從三月份找實(shí)習(xí)到現(xiàn)在婴梧,面了一些公司,掛了不少客蹋,但最終還是拿到小米塞蹭、百度、阿里讶坯、京東番电、新浪、CVTE辆琅、樂(lè)視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,243評(píng)論 11 349
  • 溫室里漱办, 最寒冷的可是人心? 寒夜里婉烟, 最炙熱的可是理想娩井? 誰(shuí)都可演成熟, 誰(shuí)都可演沉默似袁, 只有你的不羈在星空閃爍...
    藍(lán)調(diào)易拉罐閱讀 103評(píng)論 0 0
  • 多少人一旦邁出腳步 就再也不能回頭 還怎么能在出走半生時(shí)候 歸來(lái)時(shí)仍是天真少年 挫折苦痛經(jīng)驗(yàn) 慢慢教會(huì)我們成長(zhǎng) 初...
    植成喬木閱讀 208評(píng)論 0 0