熟悉ssh框架的朋友在使用struts2作为mvc框架时候,会在action类上设置成员属性对应页面上提交的参数,当程序启动的时候struts2会将request中的parameter通过反射的机制自动设置到action上。struts框架会负参数责转型等问题的处理,这样一来可以大大减少web开发过程中的重复劳动,大大降低出错的概率。

如果能将该机制底层的实现流程搞清楚,将来可以将这个功能模块移植到其他框架中,那无疑会提升整体代码的优雅性。

Java代码
<span style=“white-space: normal; background-color: #ffffff;”>import java.lang.reflect.Field;</span>
import ognl.OgnlRuntime;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ognl.OgnlValueStackFactory;
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
import com.opensymphony.xwork2.util.CompoundRoot;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * Base Action class for the Tutorial package.
 */
public class ExampleSupport extends ActionSupport {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public static void main(String[] arg) throws Exception {
        OgnlValueStackFactory factory = new OgnlValueStackFactory();
        factory.setXWorkConverter(new ExtendXWorkConverter());

        Field field = OgnlValueStackFactory.class
                .getDeclaredField(“compoundRootAccessor”);
        field.setAccessible(true);

        CompoundRootAccessor propertyAccessor = new CompoundRootAccessor();
        field.set(factory, propertyAccessor);

        factory.setContainer(new MockContainer());
        OgnlRuntime.setPropertyAccessor(CompoundRoot.class, propertyAccessor);

        ValueStack valueStack = factory.createValueStack();

        User user = new User();
        valueStack.push(user);
        valueStack.setValue(“createTime”, “2012-12-12 5/24/33″);
        valueStack.setValue(“name”, “baisui”);
        valueStack.setValue(“age”, “11″);
        valueStack.setValue(“gender”, “true”);
        valueStack.setValue(“department”, new String[] { “office” });

        System.out.println(user.getName());
        System.out.println(user.getAge());
        System.out.println(user.getDepartment());
        System.out.println(user.getGender());
        System.out.println(user.getCreateTime());

    }
}

Java代码

public class User {
    private String name;
    private Integer age;
        private Date createTime;

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    private String[] department;

    private Boolean gender;

    public String[] getDepartment() {
        return department;
    }

    public void setDepartment(String[] department) {
        this.department = department;
    }

    public Boolean getGender() {
        return gender;
    }

    public void setGender(Boolean gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}