书城计算机大话设计模式
11030400000183

第183章 4 Struts中Action的使用

大B:“由于在JUnit中,参杂了其它的模式在里面,使得命令模式的特点不太明显。我给你讲讲以命令模式在Web开发中最常见的应用――Struts中Action的使用作为例子。”

小A:“嗯。好的。”

大B:“在Struts中Action控制类是整个框架的核心,它连接着页面请求和后台业务逻辑处理。按照框架设计,每一个继承自Action的子类,都实现execute方法――调用后台真正处理业务的对象来完成任务。”

大B:“需要注意的是:继承自DispatchAction的子类,则可以一个类里面处理多个类似的操作。”

下面我们将Struts中的各个类与命令模式中的角色对号入座。

先来看下命令角色――Action控制类

public class Action{

……

/*

*可以看出,Action中提供了两个版本的执行接口,而且实现了默认的空实现。

*/

public ActionForward execute(ActionMapping mapping,

ActionForm form,

ServletRequest request,

ServletResponse response)

throws Exception{

try{

return execute(mapping,form,(HttpServletRequest)request,

(HttpServletResponse)response);

}catch(ClassCastException e){

return null;

}

}

public ActionForward execute(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception{

return null;

}

}

下面的就是请求者角色,它仅仅负责调用命令角色执行操作。

public class RequestProcessor{

……

protected ActionForward processActionPerform(HttpServletRequest request,

HttpServletResponse response,

Action action,

ActionForm form,

ActionMapping mapping)

throws IOException,ServletException{

try{

return(action。execute(mapping,form,request,response));

}catch(Exception e){

return(processException(request,response,e,form,mapping));

}

}

}

大B:“Struts框架为我们提供了以上两个角色,要使用struts框架完成自己的业务逻辑,剩下的三个角色就要由我们自己来实现了。”

小A:“那要怎么去实现啊?”

大B:“实现的步骤如下:1、很明显我们要先实现一个Action的子类,并重写execute方法。在此方法中调用业务模块的相应对象来完成任务。2、实现处理业务的业务类。3、配置struts-config。xml配置文件,将自己的Action和Form以及相应页面结合起来。4、编写jsp,在页面中显式的制定对应的处理Action。”