(转载)关于paramsPrepareParamsStack

原帖地址:
http://hi.baidu.com/%CC%AB%C6%BD%D1%F31986/blog/item/110b13b1384e805e08230259.html
转贴

paramsPrepareParamsStack在Struts 2.0中是一个很奇妙的interceptor stack,以至于很多人疑问为何不将其设置为默认的interceptor stack。paramsPrepareParamsStack主要解决了ModelDriven和Preparable的配合问题,从字面上理解来说, 这个stack的拦截器调用的顺序为:首先params,然后prepare,接下来modelDriven,最后再params。Struts 2.0的设计上要求modelDriven在params之前调用,而业务中prepare要负责准备model,准备model又需要参数,这就需要在 prepare之前运行params拦截器设置相关参数,这个也就是创建paramsPrepareParamsStack的原因。流程如下:
   1. params拦截器首先给action中的相关参数赋值,如id  
   2. prepare拦截器执行prepare方法,prepare方法中会根据参数,如id,去调用业务逻辑,设置model对象
   3. modelDriven拦截器将model对象压入value stack,这里的model对象就是在prepare中创建的
   4. params拦截器再将参数赋值给model对象
   5. action的业务逻辑执行 依据此stack,一个action的代码通常如下

public class UserAction extends ActionSupport implements ModelDriven, Preparable {
    private User user;
    private int id;
    private UserService service; // user business service

    public void setId(int id) {
        this.id = id;
    }

    /**
     * create a new user if none exists, otherwise load the user with the
     * specified id
     */
    public void prepare() throws Exception {
        if (id == 0) {
            user = new User();
        } else {
            user = service.findUserById(id);
        }
    }

    public Object getModel() {
        return user;
    }

    /**
     * create or update the user and then view the created user
     */
    public String update() {
        if (id == 0) {
            service.create(user);
        } else {
            service.update(user);
        }
        return "redirect";
    }

    /**
     * delete the user and go to a default home page
     */
    public String delete() {
        service.deleteById(id);
        return "home";
    }

    /**
     * show the page allowing the user to view the existing data
     */
    public String view() {
        return "view";
    }

    /**
     * show the page allowing the user to view the existing data and change the
     * values
     */
    public String edit() {
        return "input";
    }

在上述代码中,edit和view都不需要根据id再为界面准备数据,因为prepare方法已经准备好了model,这些方法很简单。对于update 方法,prepare首先会从数据库中加载数据,然后params拦截器会将参数值付给model,在update直接更新就可以,不会出现数据被乱更新 的情况。象Hibernate框架,会判断哪些字段更新了,然后进行更新,性能也不会损失。
通过paramsPrepareParamsStack可以让流程更明确,代码更简洁,也更利于大家的交流。

posted on 2011-11-16 15:39 AK47 阅读(425) 评论(0)  编辑  收藏 所属分类: Structs


只有注册用户登录后才能发表评论。


网站导航:
 
<2011年11月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜