package com.coderising.litestruts;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Struts {
public static View runAction(String actionName, Map<String,String> parameters) throws Exception {
/*
0. 读取配置文件struts.xml
1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象)
据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是
("name"="test" , "password"="1234") ,
那就应该调用 setName和setPassword方法
2. 通过反射调用对象的execute 方法, 并获得返回值,例如"success"
3. 通过反射找到对象的所有getter方法(例如 getMessage),
通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} ,
放到View对象的parameters
4. 根据struts.xml中的 <result> 配置,以及execute的返回值, 确定哪一个jsp,
放到View对象的jsp字段中。
*/
SAXReader reader = new SAXReader();
Document doc = reader.read("./src/struts.xml");
Element root = doc.getRootElement();
Element el = root.element("action");
Attribute attr = el.attribute("class");
String value = attr.getValue();
System.out.println(attr.getValue());
Class<?> clazz = Class.forName(value);
LoginAction login =(LoginAction) clazz.newInstance();
Method setN = clazz.getMethod("setName", String.class);
setN.invoke(login, "test");
Method setP = clazz.getMethod("setPassword", String.class);
setP.invoke(login, "1234");
Method getM = clazz.getMethod("execute", null);
String str = (String) getM.invoke(login, null);
System.out.println(str);
/*PropertyDescriptor pro = new PropertyDescriptor("name", LoginAction.class);
Method readM = pro.getReadMethod();
String message = (String) readM.invoke(login, null);*/
String bean = BeanUtils.getProperty(login, "name");
System.out.println(bean);
return null;
}
}