Struts ActionFrom 原理 实现

原理java

上图: web

 

 

 

 

简单实现:apache

  
  
  
  
  1. package com.vili.wems.web.webservice.ma.information; 
  2. import java.beans.IntrospectionException; 
  3. import java.beans.Introspector; 
  4. import java.beans.PropertyDescriptor; 
  5. import java.lang.reflect.InvocationTargetException; 
  6. import java.util.Enumeration; 
  7.  
  8. import javax.servlet.http.HttpServletRequest; 
  9.  
  10. import org.apache.commons.beanutils.BeanUtils; 
  11. import org.apache.struts.action.ActionForm; 
  12.  
  13. public class FormUtils { 
  14.  
  15.   public static void fillForm(HttpServletRequest request,String formFullClassName,String formName){ 
  16.   try { 
  17.    //1.利用JAVA的反射机制得到当前传进来的BEAN对象 
  18.    ActionForm form =(ActionForm)Class.forName(formFullClassName).newInstance(); 
  19.    PropertyDescriptor[] properties = Introspector.getBeanInfo(form.getClass()).getPropertyDescriptors(); 
  20.     
  21.    //2.取得页面中的传递元素 
  22.    Enumeration formParameters = request.getParameterNames(); 
  23.        
  24.    //3.遍历元素 
  25.    while(formParameters.hasMoreElements()){ 
  26.     String parameterName = (String)formParameters.nextElement(); 
  27.      
  28.     for(PropertyDescriptor property:properties){ 
  29.      String properyName = property.getName(); 
  30.       
  31.      //4.比较两个对象的名称是否相等,若是相等则填充FORM 
  32.      if(parameterName.equals(properyName)) 
  33.      { 
  34.       String propertyValue = request.getParameter(properyName); 
  35.       BeanUtils.setProperty(form, properyName, propertyValue); 
  36.      } 
  37.     } 
  38.      
  39.    } 
  40.     
  41.    //5.保存填充好的对象 
  42.    request.getSession().setAttribute(formName, form); 
  43.   } catch (InstantiationException e) { 
  44.    // TODO Auto-generated catch block 
  45.    e.printStackTrace(); 
  46.   } catch (IllegalAccessException e) { 
  47.    // TODO Auto-generated catch block 
  48.    e.printStackTrace(); 
  49.   } catch (ClassNotFoundException e) { 
  50.    // TODO Auto-generated catch block 
  51.    e.printStackTrace(); 
  52.   } catch (IntrospectionException e) { 
  53.    // TODO Auto-generated catch block 
  54.    e.printStackTrace(); 
  55.   } catch (InvocationTargetException e) { 
  56.    // TODO Auto-generated catch block 
  57.    e.printStackTrace(); 
  58.   } 
  59.    
  60.   }  
  61.