原理
上图:
简单实现:
- 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();
- }
- }
- }
转载于:https://blog.51cto.com/unknown/1007321