SSH框架之Struts(4)――Struts查漏補缺BeanUtils在Struts1中
來源:程序員人生 發布時間:2014-11-07 08:39:24 閱讀次數:2456次
在上篇博客SSH框架之Struts(3)――Struts的運行流程之核心方法,我們提到RequestProcessor中的processPopulate()是用來為為ActionForm 填充數據,它是怎樣實現將表單數據放入到1個ActionForm中的呢?――第3方工具,BeanUtils,相對來講,這是1個非常重要的用來操作javaBean的服務。
public static void populate(
Object bean,
String prefix,
String suffix,
HttpServletRequest request)
throws ServletException {
// Build a list of relevant request parameters from this request
HashMap properties = new HashMap();
// Iterator of parameter names
Enumeration names = null;
// Map for multipart parameters
Map multipartParameters = null;
String contentType = request.getContentType();
String method = request.getMethod();
boolean isMultipart = false;
if (bean instanceof ActionForm) {
((ActionForm) bean).setMultipartRequestHandler(null);
}
MultipartRequestHandler multipartHandler = null;
if ((contentType != null)
&& (contentType.startsWith("multipart/form-data"))
&& (method.equalsIgnoreCase("POST"))) {
// Get the ActionServletWrapper from the form bean
ActionServletWrapper servlet;
if (bean instanceof ActionForm) {
servlet = ((ActionForm) bean).getServletWrapper();
} else {
throw new ServletException(
"bean that's supposed to be "
+ "populated from a multipart request is not of type "
+ ""org.apache.struts.action.ActionForm", but type "
+ """
+ bean.getClass().getName()
+ """);
}
// Obtain a MultipartRequestHandler
multipartHandler = getMultipartHandler(request);
if (multipartHandler != null) {
isMultipart = true;
// Set servlet and mapping info
servlet.setServletFor(multipartHandler);
multipartHandler.setMapping(
(ActionMapping) request.getAttribute(Globals.MAPPING_KEY));
// Initialize multipart request class handler
multipartHandler.handleRequest(request);
//stop here if the maximum length has been exceeded
Boolean maxLengthExceeded =
(Boolean) request.getAttribute(
MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
return;
}
//retrieve form values and put into properties
multipartParameters = getAllParametersForMultipartRequest(
request, multipartHandler);
names = Collections.enumeration(multipartParameters.keySet());
}
}
if (!isMultipart) {
names = request.getParameterNames();
}
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String stripped = name;
if (prefix != null) {
if (!stripped.startsWith(prefix)) {
continue;
}
stripped = stripped.substring(prefix.length());
}
if (suffix != null) {
if (!stripped.endsWith(suffix)) {
continue;
}
stripped = stripped.substring(0, stripped.length() - suffix.length());
}
Object parameterValue = null;
if (isMultipart) {
parameterValue = multipartParameters.get(name);
} else {
parameterValue = request.getParameterValues(name);
}
// Populate parameters, except "standard" struts attributes
// such as 'org.apache.struts.action.CANCEL'
if (!(stripped.startsWith("org.apache.struts."))) {
properties.put(stripped, parameterValue);
}
}
// Set the corresponding properties of our bean
try {
BeanUtils.populate(bean, properties);
} catch(Exception e) {
throw new ServletException("BeanUtils.populate", e);
} finally {
if (multipartHandler != null) {
// Set the multipart request handler for our ActionForm.
// If the bean isn't an ActionForm, an exception would have been
// thrown earlier, so it's safe to assume that our bean is
// in fact an ActionForm.
((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
}
}
}
這段實現的前半部份是關于上傳的代碼,如果用到上傳功能的可以仔細瀏覽以下前邊部份的代碼,我們這里不做解釋,可以往下看。
if (!isMultipart) {
names = request.getParameterNames();
}
這是用來獲得到表單所有的名稱,進而為屬性值的Copy和轉換做準備
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String stripped = name;
if (prefix != null) {
if (!stripped.startsWith(prefix)) {
continue;
}
stripped = stripped.substring(prefix.length());
}
if (suffix != null) {
if (!stripped.endsWith(suffix)) {
continue;
}
stripped = stripped.substring(0, stripped.length() - suffix.length());
}
Object parameterValue = null;
if (isMultipart) {
parameterValue = multipartParameters.get(name);
} else {
parameterValue = request.getParameterValues(name);
}
}
// Populate parameters, except "standard" struts attributes
// such as 'org.apache.struts.action.CANCEL'
if (!(stripped.startsWith("org.apache.struts."))) {
properties.put(stripped, parameterValue);
}
遍歷表單所有的名稱,并通過parameterValue = request.getParameterValues(name);取得名稱對應的value值。以后就是通過properties.put(stripped, parameterValue);將名稱作為key,名稱對應的值作為value放入到map中。
// Set the corresponding properties of our bean
try {
BeanUtils.populate(bean, properties);
} catch(Exception e) {
throw new ServletException("BeanUtils.populate", e);
} finally {
if (multipartHandler != null) {
// Set the multipart request handler for our ActionForm.
// If the bean isn't an ActionForm, an exception would have been
// thrown earlier, so it's safe to assume that our bean is
// in fact an ActionForm.
((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
}
}
}
在這里,主要是調用第3方服務BeanUtils來實現屬性值的轉換和賦值。這個方法會遍歷ActionForm的值的類型,并且講Map中的值的類型改成和ActionForm對應的類型。到這里processPopulate的方法就實現終了。BeanUtils的populate方法是將從form表單取到的名稱和值映照到對應的ActionForm中,源碼以下
public static void populate(Object bean, Map properties)
throws IllegalAccessException, InvocationTargetException {
// Do nothing unless both arguments have been specified
if ((bean == null) || (properties == null)) {
return;
}
if (log.isDebugEnabled()) {
log.debug("BeanUtils.populate(" + bean + ", " +
properties + ")");
}
// Loop through the property name/value pairs to be set
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
// Identify the property name and value(s) to be assigned
String name = (String) names.next();
if (name == null) {
continue;
}
Object value = properties.get(name);
// Perform the assignment for this property
setProperty(bean, name, value);
}
}
BeanUtils.populate(bean, properties);履行完,至此,完成了form表單數據到ActionForm的映照。
BeanUtils作為1個操作javaBean的第3方服務,這里引出BeanUtils,下篇通過實例來了解和學習BeanUtils。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈