Struts(十八):通过CURD来学习PrepareInterceptor拦截器

  • PrepareInterceptor拦截器的用法:

1、若Action实现了Preparable接口,则Action方法需实现prepare()方法;

2、PrepareInterceptor拦截器Struts将调用prepare()方法;

    @Override
    public Member getModel() {
        return this.member;
    }

    @Override
    public void prepare() throws Exception {
        // 如果没有id请求参数,说明为create
        if (this.id == null) {
            this.member = new Member();
        }
        // 如果有id请求参数,说明为edit
        else {
            this.member = memberDao.get(this.id);
        }
    }

3、PrepareInteceptor拦截器根据firstCallPrepareDo属性决定获取prepareActionMethodName、prepareDoActionMethodName的顺序,默认情况下先获取prepareActionMethodName,如果没有该方法,就寻找prepareDoActionMethodName()。如果找到对应的方法就调用该方法,若都不存在,则不执行;

4、PrepareInterceptor拦截器会根据alwaysInvokePrepare属性决定是否执行prepare()方法,默认该属性为true,如果要修改该属性值为false,则需要在struts.xml配置文件中修改,具体重写拦截器属性值的方案参考:http://struts.apache.org/docs/interceptors.html#Interceptors-InterceptorParameterOverriding(默认提供了三种重写拦截器属性值的方法)。

  • 使用paramsPrepareParamsStack拦截器栈

1、paramsPrepareParams从字面上理解,这个stack的拦截器调用的顺序为:首先调用params,然后调用prepare,接下来调用modelDriven,然后再调用params;

2、Struts2.0的设计上要求modelDriven在params之前调用,而业务中prepare要负责准备model,准备model又需要参数,这就需要在prepare之前调用params拦截器设置相关参数,这个也就是创建paramsPrepareParamsStack的原因。

3、执行流程如下:

3.1、params拦截器首先给action中的相关参数赋值,如id;

3.2、prepare拦截器执行prepare方法,prepare方法中会根据参数,如id,去调用业务逻辑,设置model对象;

3.3、modelDriven拦截器将model对象压入valuestack,这里的model对象就是在prepare中创建的;

3.4、params拦截器在将参数赋值给model对象;

3.5、action的业务逻辑执行。

  •  测试应用:

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- <constant name="struts.action.extension" value="action" /> <constant 
        name="struts.enable.DynamicMethodInvocation" value="true" /> -->
    <constant name="struts.ognl.allowStaticMethodAccess" value="true" />
    <constant name="struts.devMode" value="false" />

    <package name="default" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor-stack name="myParamsPrepareParamsStack">
                <interceptor-ref name="paramsPrepareParamsStack">
                    <param name="prepare.alwaysInvokePrepare">false</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="myParamsPrepareParamsStack" />
        
        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping result="error"
                exception="java.lang.ArithmeticException"></exception-mapping>
        </global-exception-mappings>

        <action name="member-*" class="com.dx.struts.actions.MemberAction"
            method="{1}">
            <result name="{1}">/member-{1}.jsp</result>
            <result name="delete" type="redirectAction">member-list</result>
            <result name="modify" type="redirectAction">member-list</result>
            <result name="create" type="redirectAction">member-list</result>
        </action>
    </package>
</struts>

MemberAction.java

/**
 * @author Administrator
 *
 */
package com.dx.struts.actions;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.dx.struts.dao.MemberDao;
import com.dx.struts.entity.Member;

/**
 * ModelDriven 和Preparable拦截器
 */
public class MemberAction implements RequestAware, ModelDriven<Member>, Preparable {
    private MemberDao memberDao = new MemberDao();
    private Member member;
    private Long id;

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

    public String list() {
        List<Member> members = memberDao.getMembers();
        request.put("members", members);

        return "list";
    }

    public void prepareView() {
        this.member = memberDao.get(id);
    }

    public String view() {
        return "view";
    }

    public String delete() {
        memberDao.remove(this.id);

        return "delete";
    }

    public void prepareEdit() {
        this.member = memberDao.get(id);
    }

    public String edit() {
        return "edit";
    }

    public void prepareSave() {
        this.member = new Member();
    }

    public String save() {
        // 1、获取传入的id:member.getId();
        // 2、根据id获取member对象;
        Member member_ = memberDao.get(this.member.getId());

        // 3、赋值栈顶对象的属性:此时栈顶对象为member对象。
        member_.setAge(this.member.getAge());
        member_.setName(this.member.getName());
        member_.setGender(this.member.getGender());

        return "modify";
    }

    public void prepareCreate() {
        this.member = new Member();
    }

    public String create() {
        member.setId(new Date().getTime());
        memberDao.add(member);

        return "create";
    }

    private Map<String, Object> request;

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }

    @Override
    public Member getModel() {
        return this.member;
    }

    @Override
    public void prepare() throws Exception {
        System.out.println("prepare function......");
    }
}

好处:

可以避免资源浪费,对每个Action的方法可以自己根据自己的需要提前处理一些业务信息。

 

posted @ 2017-03-29 20:01  cctext  阅读(826)  评论(0编辑  收藏  举报