代码展示:

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
    
    @Resource
    protected DepartmentService departmentService;
    
    @Resource
    protected UserService  userService;
    
    @Resource
    protected RoleService roleService;
    
    private Class<T> modelClass=null;
    
    
    protected T model=null;
    
    public BaseAction() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
        try {
            model=modelClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
        System.out.println("---> clazz = " + modelClass);
    }

    
    @Override
    public T getModel() {
        // TODO Auto-generated method stub
        return model;
    }

总结:对于公共模块,或者是一些业务类对象的注入,我们可以创建一个baseAction的基础抽象类,让基础抽象类去实现ModelDriven,实现这个接口 具体代码:

implements ModelDriven<T>

,它会自动将前端传过来的数据封装成model对象,我们控制层调用数据的时候,可以直接从封装之后的对象中获取想要的属性字段

注意:封装成这个model对象的时候,会出现前端传递过来的字段为null;我们这个时候想要在struts2的action类中编写字段和提供字段的get和set方法类接收参数时,就不需要编写了,直接从model封装对象中获取数据,直接将获取的数据即可;