作用:在從request 裏獲取指定屬性的值之前,動態設置默認參數。
方法及其功能:通常服務端,從Web 獲取參數,當不能從前臺獲取完整參數時發生異常。若要避免也常,可以在服務端轉發請求前,爲其動態設置默認參數。當未能從前臺獲取參數時,使用默認參數。
public static [DataType] get[DataType]( Object bean, ServletRequest req, String param )
{
return get[DataType](bean, req, param, GetterUtil.DEFAULT_[DataType]);
}
public static [DataType] get[DataType]( Object bean,
ServletRequest req,
String param,
[DataType] defaultValue )
{
[DataType] beanValue = null;
// (1)判斷傳入的bean 對象是否爲空,若不爲空則判斷傳入的對象中是否包涵名爲param 的屬性。
// 若包涵則將名爲param 的屬性的值賦給beanValue。
if (bean != null) {
try {
beanValue =
([DataType])PropertyUtils.getSimpleProperty(bean, param);
}
catch (Exception e) {
_log.error(e);
}
}
//(2)判斷是否從對象bean 中的獲取名爲param 的屬性值。若未獲取到則從request 中查找名爲param
// 的屬的值。若仍然不包含該值則用defaulValue 對其賦值。
if (beanValue == null) {
return ParamUtil.get(req, param, defaultValue);
}
//(3)若從對象bean 中獲取了值beanValue,則以beanValue 作爲默認值,從request 中查找param 屬性。
else {
return ParamUtil.get(req, param, beanValue.[DataType]Value());
}
}
注意:區別於ParamUtil 類,ParamUtil 的一系列get 方法也能夠預設默認值,但是必須在知道具體屬性的前提下,顯式的爲期望獲取的屬性設置默認值;而BeanParamUtil 可以動態的利用對象爲其設置初始值,而不需要人爲的分解對象各個屬性再爲其分配初始值。