我做tag解析时深入了解过这个问题,在JAVA中,通过WEB服务器传递数据方式分两种,一种是session,一种是request,使用方法如下:
1.使用request传:
request.setAttribute("beanobject", sample); //其中sample为bean
2.使用session传:
HttpSession s = request.getSession();
s.setAttribute("beanobject", sample); //其中sample为bean
传递时,数据还原成object并且放在request或session中传递,到达目的地后再还原成原来的类型,struts在这方面做得比较好,他在BeanUtil中提供了相应的还原接口,在写
************************ Main.java ************************
package reflect;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
Bean1 bean1 = new Bean1();
System.out.println( Reflect.get(bean1, "getName", 0) );
System.out.println( Reflect.get(bean1, "getOld", 0) );
System.out.println( Reflect.get(bean1, "getName", 1) );
System.out.println( Reflect.get(bean1, "getOld", 1) );
System.out.println( Reflect.get(bean1, "getName", 2) );
System.out.println( Reflect.get(bean1, "getOld", 2) );
System.out.println( Reflect.get(bean1, "getName", 3) );
System.out.println( Reflect.get(bean1, "getOld", 3) );
System.out.println( Reflect.get(bean1, "getName", 4) );
System.out.println( Reflect.get(bean1, "getOld", 4) );
Bean2 bean2 = new Bean2();
System.out.println( Reflect.get(bean2, "getMember", 0) );
System.out.println( Reflect.get(bean2, "getYear", 0) );
System.out.println( Reflect.get(bean2, "getMember", 1) );
System.out.println( Reflect.get(bean2, "getYear", 1) );
System.out.println( Reflect.get(bean2, "getMember", 2) );
System.out.println( Reflect.get(bean2, "getYear", 2) );
System.out.println( Reflect.get(bean2, "getMember", 3) );
System.out.println( Reflect.get(bean2, "getYear", 3) );
System.out.println( Reflect.get(bean2, "getMember", 4) );
System.out.println( Reflect.get(bean2, "getYear", 4) );
}
}
************************ Reflect.java ************************
package reflect;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Reflect {
public static String get(Object object, String methodname, int i){
Class cls = object.getClass();
Object ret;
try {
Method method = cls.getMethod(methodname, null);
ret = method.invoke(cls.newInstance(), null);
ArrayList array = new ArrayList();
if (ret.getClass().isArray()) {
ret = Array.get(ret, i);
}
} catch (Exception e) {
ret = null;
}
if(ret == null){
return null;
}
return ret.toString();
}
}
************************ Bean1.java ************************
package reflect;
public class Bean1 {
String[] name = {"赵","钱","孙","李"};
int[] old = {28, 27, 32, 26};
public String[] getName(){
return name;
}
public int[] getOld(){
return old;
}
}
************************ Bean2.java ************************
package reflect;
public class Bean2 {
String[] member = {"张","刘","王","方"};
int[] year = {31, 28, 30, 36};
public String[] getMember(){
return member;
}
public int[] getYear(){
return year;
}
}
大家注意:主要是Reflect.java,你只要将bean的名字和getproperty的名字给他,他就能把数据传回给你.