SpringMVC中利用@InitBinder來(lái)對(duì)頁(yè)面數(shù)據(jù)進(jìn)行解析綁定的方法
在使用SpingMVC框架的項(xiàng)目中,經(jīng)常會(huì)遇到頁(yè)面某些數(shù)據(jù)類型是Date、Integer、Double等的數(shù)據(jù)要綁定到控制器的實(shí)體,或者控制器需要接受這些數(shù)據(jù),如果這類數(shù)據(jù)類型不做處理的話將無(wú)法綁定。
這里我們可以使用注解@InitBinder來(lái)解決這些問題,這樣SpingMVC在綁定表單之前,都會(huì)先注冊(cè)這些編輯器。一般會(huì)將這些方法些在BaseController中,需要進(jìn)行這類轉(zhuǎn)換的控制器只需繼承BaseController即可。其實(shí)Spring提供了很多的實(shí)現(xiàn)類,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是夠用的。
demo如下:
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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot整合JPA使用多個(gè)數(shù)據(jù)源的方法步驟
這篇文章主要給大家介紹了關(guān)于Spring Boot整合JPA使用多個(gè)數(shù)據(jù)源的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Elasticsearch索引結(jié)構(gòu)與算法解析
?作為搜索引擎的一部分,ES自然具有速度快、結(jié)果準(zhǔn)確、結(jié)果豐富等特點(diǎn),那么ES是如何達(dá)到“搜索引擎”級(jí)別的查詢效率呢?首先是索引,其次是壓縮算法,接下來(lái)我們就一起了解下ES的索引結(jié)構(gòu)和壓縮算法2023-04-04
java中ExecutorService創(chuàng)建方法總結(jié)
在本篇文章里小編給大家整理了一篇關(guān)于java中ExecutorService創(chuàng)建方法總結(jié),有興趣的朋友們可以參考下。2021-01-01
java多線程之線程,進(jìn)程和Synchronized概念初解
這篇文章主要介紹了java多線程之線程,進(jìn)程和Synchronized概念初解,涉及進(jìn)程與線程的簡(jiǎn)單概念,實(shí)現(xiàn)多線程的方式,線程安全問題,synchronized修飾符等相關(guān)內(nèi)容,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-11-11
SpringBoot響應(yīng)處理實(shí)現(xiàn)流程詳解
這篇文章主要介紹了SpringBoot響應(yīng)處理實(shí)現(xiàn)流程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10

