??? 下面是我在就業(yè)網(wǎng)重構(gòu)時用到的一個java類,其中就是對BeanUtils進行了簡單的封裝。
???import java.sql.Date;
???import java.util.Map;
?? import org.apache.commons.beanutils.BeanUtils;
?? import org.apache.commons.beanutils.ConvertUtils;
?? import org.apache.commons.beanutils.converters.SqlDateConverter;
?? public class NullSafeBeanUtils {
??
?? public final static String EMPTY_STRING = "";
?
?? public static boolean isNull(Object obj) {
?????? return obj == null;
?? }
?? public static String getProperty(Object bean, String property) {
????? ?if (bean == null) {
?????????? ?return EMPTY_STRING;
????? ?}
??? ?try {
???????? ?String str = BeanUtils.getProperty(bean, property);
???????? ?if (str == null) {
????????????? return EMPTY_STRING;
??????? ?}
??????? return str;
???? } catch (Exception e) {
??????? ?return EMPTY_STRING;
?? }
? }
??public static void populate(Object bean, Map props) {
??? ?if (bean == null) {
??????? return;
???? }
?? ?try {
???? SqlDateConverter con = new SqlDateConverter(new Date(System.currentTimeMillis()));
????? ConvertUtils.register(con, java.sql.Date.class);
????? BeanUtils.populate(bean, props);
?? } catch (Exception e) {
??? ?e.printStackTrace();
?? }
?}
?//?此處省略了一些其他代碼
?}
?
??? 在這里,poplulate方法就是我用來自動填充參數(shù)的。要實現(xiàn)自動填充,只需簡單調(diào)用此方法就行了。看一個例子:
??? JobExperience jobExp = new JobExperience();
??? NullSafeBeanUtils.populate(jobExp, request.getParameterMap());
?? 是不是簡單了許多?要注意的是表單的各輸入字段名要和bean的各屬性名對應(yīng)才能自動填充。另外NullSafeBeanUtils 的getProperty方法也很有用,可以避免寫
?? if (bean != null) {
????? yyy = bean.getXXX()==null?"":bean.getXXX()
???}
?? 這樣的代碼,直接寫NullSafeBeanUtils.getProperty(bean, "XXX")就可以了。
只有注冊用戶登錄后才能發(fā)表評論。 | ||
![]() |
||
網(wǎng)站導航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||
相關(guān)文章:
|
||