原理java
上圖: web
簡單實現:apache
- package com.vili.wems.web.webservice.ma.information;
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- import java.util.Enumeration;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.commons.beanutils.BeanUtils;
- import org.apache.struts.action.ActionForm;
- public class FormUtils {
- public static void fillForm(HttpServletRequest request,String formFullClassName,String formName){
- try {
- //1.利用JAVA的反射機制得到當前傳進來的BEAN對象
- ActionForm form =(ActionForm)Class.forName(formFullClassName).newInstance();
- PropertyDescriptor[] properties = Introspector.getBeanInfo(form.getClass()).getPropertyDescriptors();
- //2.取得頁面中的傳遞元素
- Enumeration formParameters = request.getParameterNames();
- //3.遍歷元素
- while(formParameters.hasMoreElements()){
- String parameterName = (String)formParameters.nextElement();
- for(PropertyDescriptor property:properties){
- String properyName = property.getName();
- //4.比較兩個對象的名稱是否相等,若是相等則填充FORM
- if(parameterName.equals(properyName))
- {
- String propertyValue = request.getParameter(properyName);
- BeanUtils.setProperty(form, properyName, propertyValue);
- }
- }
- }
- //5.保存填充好的對象
- request.getSession().setAttribute(formName, form);
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IntrospectionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }