网站首页
JSP空间
动态资讯
开源项目
技术文档
资源下载
J2EE资源
客户论坛
在线支付
 
  技术文档>>JAVA>>高级技术>>设计模式>查看文档  
  设计模式:设计自己的mvc框架     
  文章作者:未知  文章来源:中国IT实验室  
  查看:111次  录入:管理员--2007-11-20  
  源代码放在sharesources@126.com的邮箱的收件箱里,用户名:sharesource,密码:javafans
希望保留给有用的人,谢谢。

    取这样一个标题太大,吸引眼球嘛@_@。

    事实是最近读《j2ee设计模式》讲述表达层模式的那几章,书中有一个前端控制器+command模式的workflow例子,就琢磨着可以很简单地扩展成一个mvc框架。花了一个下午改写了下,对书中所述的理解更为深入。我想这也许对于学习和理解设计模式,以及初次接触struts等mvc框架的人可能有点帮助。因为整个模型类似于struts,我把它取名叫strutslet^_^。学习性质,切勿认真。

(一)完整的类图如下:


1。前端控制器(frontcontroller):前端控制器提供了一个统一的位置来封装公共请求处理,它的任务相当简单,执行公共的任务,然后把请求转交给相应的控制器。在strutslet中,前端控制器主要作用也在于此,它初始化并解析配置文件,接受每个请求,并简单地把请求委托给调度器(dispatcher),由调度器执行相应的动作(action)。调度器把action返回的url返回给frontcontroller,frontcontroller负责转发。

2。action接口:command模式很好的例子,它是一个命令接口,每一个实现了此接口的action都封装了某一个请求:新增一条数据记录并更新model,或者把某个文件写入磁盘。命令解耦了发送者和接受者之间联系。 发送者调用一个操作,接受者接受请求执行相应的动作,因为使用command模式解耦,发送者无需知道接受者任何接口。

3。dispatcher:调度器,负责流程的转发,负责调用action去执行业务逻辑。由调度器选择页面和action,它去除了应用行为和前端控制器间的耦合。调度器服务于前端控制器,它把model的更新委托给action,又提供页面选择给frontcontroller

4。actionforward:封装了转向操作所需要信息的一个模型,包括name和转向url

5。actionmodel:解析配置文件后,将每一个action封装成一个actionmodel对象,所有actionmodel构成一个map,并存储在servletcontext中,供整个框架使用。


(二)源代码简单分析
1。action接口,只有一个execute方法,任何一个action都只要实现此接口,并实现相应的业务逻辑,最后返回一个actionforward,提供给dispacher调用。
  1. public interface action {
  2.  public actionforward execute(httpservletrequest request,servletcontext context); 
  3. }


比如,我们要实现一个登陆系统(demo的例子),loginaction验证用户名和密码,如果正确,返回success页面,如果登陆失败,返回fail页面:
  1. public class loginaction implements action {
  2.  private string name="";
  3.  public actionforward execute(httpservletrequest request,
  4.    servletcontext context) {
  5.   string username=request.getparameter("username");
  6.   string password=request.getparameter("password");
  7.         if(username.equals("dennis")&&password.equals("123")){
  8.       request.setattribute("name", name);
  9.       return actionforward.success;  //登陆成功,返回success
  10.         }else
  11.          return actionforward.fail;    //否则,返回fail
  12.  }



 

2.还是先来看下两个模型:actionforward和actionmodel,没什么东西,属性以及相应的getter,setter方法:

  1. /**
  2.  * 类说明:转向模型
  3.  * @author dennis
  4.  *
  5.  * */
  6. public class actionforward {
  7.  private string name;      //forward的name
  8.  private string viewurl;   //forward的url
  9.  public static final actionforward success=new actionforward("success");
  10.  public static final actionforward fail=new actionforward("fail");
  11.  public  actionforward(string name){
  12.   this.name=name;
  13.  }
  14.  public actionforward(string name, string viewurl) {
  15.   super();
  16.   this.name = name;
  17.   this.viewurl = viewurl;
  18.  }
  19.  //...name和viewurl的getter和setter方法
  20. }   

我们看到actionforward预先封装了success和fail对象。
  1. public class actionmodel {
  2.  private string path; // action的path
  3.  private string classname; // action的class
  4.  private map<string, actionforward> forwards; // action的forward
  5.  public actionmodel(){}
  6.  public actionmodel(string path, string classname,
  7.    map<string, actionforward> forwards) {
  8.   super();
  9.   this.path = path;
  10.   this.classname = classname;
  11.   this.forwards = forwards;
  12.  }
  13.  //...相应的getter和setter方法     
  14. }


3。知道了两个模型是什么样,也应该可以猜到我们的配置文件大概是什么样的了,与struts的配置文件格式类似:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <actions>
  3.   <action path="/login"
  4.           class="com.strutslet.demo.loginaction">
  5.      <forward name="success" url="hello.jsp"/>
  6.      <forward name="fail" url="fail.jsp"/>
  7.    </action>       
  8. </actions>

path是在应用中将被调用的路径,class指定了调用的哪个action,forward元素指定了转向,比如我们这里如果是success就转向hello.jsp,失败的话转向fail.jsp,这里配置了demo用到的loginaction。

4。dispacher接口,主要是getnextpage方法,此方法负责获得下一个页面将导向哪里,提供给前端控制器转发。
  1. public interface dispatcher {
  2.  public void setservletcontext(servletcontext context);
  3.  public string getnextpage(httpservletrequest request,servletcontext context);
  4. }


5。5。原先书中实现了一个workflow的dispatcher,按照顺序调用action,实现工作流调用。而我们所需要的是根据请求的path调用相应的action,执行action的execute方法返回一个actionforward,然后得到actionforward的viewurl,将此viewurl提供给前端控制器转发,看看它的getnextpage方法:

  1. public string getnextpage(httpservletrequest request, servletcontext context) {
  2.   setservletcontext(context);
  3.   map<string, actionmodel> actions = (map<string, actionmodel>) context
  4.     .getattribute(constant.actions_attr);   //从servletcontext得到所有action信息
  5.   string reqpath = (string) request.getattribute(constant.request_attr);//发起请求的path
  6.   actionmodel actionmodel = actions.get(reqpath);  //根据path得到相应的action
  7.   string forward_name = "";
  8.   actionforward actionforward;
  9.   try {
  10.    class c = class.forname(actionmodel.getclassname());  //每个请求对应一个action实例
  11.    action action = (action) c.newinstance();
  12.    actionforward = action.execute(request, context);  //执行action的execute方法
  13.    forward_name = actionforward.getname();
  14.    
  15.   } catch (exception e) {
  16.    log.error("can not find action "+actionmodel.getclassname());
  17.    e.printstacktrace();
  18.   }
  19.   actionforward = actionmodel.getforwards().get(forward_name);
  20.   if (actionforward == null) {
  21.    log.error("can not find page for forward "+forward_name);
  22.    return null;
  23.   } else
  24.    return actionforward.getviewurl();      //返回actionforward的viewurl
  25.  }



 

6。前端控制器(frontcontroller),它的任务我们已经很清楚,初始化配置文件;存储所有action到servletcontext供整个框架使用;得到发起请求的path,提供给dispachter查找相应的action;调用dispatcher,执行getnextpage方法得到下一个页面的url并转发:

  1. public void init() throws servletexception {
  2.   //初始化配置文件
  3.   servletcontext context=getservletcontext();
  4.   string config_file =getservletconfig().getinitparameter("config");
  5.   string dispatcher_name=getservletconfig().getinitparameter("dispatcher");
  6.   if (config_file == null || config_file.equals(""))
  7.    config_file = "/web-inf/strutslet-config.xml"//默认是/web-inf/下面的strutslet-config
  8.   if(dispatcher_name==null||dispatcher_name.equals(""))
  9.    dispatcher_name=constant.default_dispatcher;
  10.     
  11.   try {
  12.    map<string, actionmodel> resources = configutil.newinstance()  //工具类解析配置文件
  13.      .parse(config_file, context);
  14.    context.setattribute(constant.actions_attr, resources);  //存储在servletcontext中
  15.    log.info("初始化strutslet配置文件成功");
  16.   } catch (exception e) {
  17.    log.error("初始化strutslet配置文件失败");
  18.    e.printstacktrace();
  19.   }
  20.   //实例化dispacher
  21.   try{
  22.    class c = class.forname(dispatcher_name);
  23.       dispatcher dispatcher = (dispatcher) c.newinstance();
  24.       context.setattribute(constant.dispatcher_attr, dispatcher); //放在servletcontext
  25.       log.info("初始化dispatcher成功");
  26.   }catch(exception e) {
  27.     log.error("初始化dispatcher失败");
  28.       e.printstacktrace();
  29.   }
  30.   .....


doget()和dopost方法我们都让它调用process方法:
  1. protected void process(httpservletrequest request,
  2.    httpservletresponse response) throws servletexception, ioexception {
  3.   servletcontext context = getservletcontext();
  4.         //获取action的path 
  5.   string requri = request.getrequesturi();
  6.   int i=requri.lastindexof(".");
  7.   string contextpath=request.getcontextpath();
  8.   string path=requri.substring(contextpath.length(),i);
  9.   
  10.   request.setattribute(constant.request_attr, path);
  11.   dispatcher dispatcher = (dispatcher) context.getattribute(constant.dispatcher_attr);
  12.   // make sure we don't cache dynamic data
  13.   response.setheader("cache-control""no-cache");
  14.   response.setheader("pragma""no-cache");
  15.   // use the dispatcher to find the next page
  16.   string nextpage = dispatcher.getnextpage(request, context);//调用dispatcher的getnextpage
  17.   // forward control to the view
  18.   requestdispatcher forwarder = request.getrequestdispatcher("/"
  19.     + nextpage);
  20.   forwarder.forward(request, response);  //转发页面
  21.  }


7。最后,web.xml的配置就非常简单了,配置前端控制器,提供启动参数(配置文件所在位置,为空就查找/web-inf/下面的strutslet-config.xml文件),我们把所有以action结尾的请求都交给frontcontroller处理:
  1. <servlet>
  2.     <servlet-name>strutsletcontroller</servlet-name>
  3.     <servlet-class>com.strutslet.core.frontcontroller</servlet-class>
  4.     <!--  
  5.     <init-param>
  6.          <param-name>config</param-name>
  7.          <param-value>/web-infstrutslet-config.xml</param-value>
  8.     </init-param>
  9.     -->
  10.        <load-on-startup>0</load-on-startup>
  11.   </servlet>
  12.  <servlet-mapping>
  13.     <servlet-name>strutsletcontroller</servlet-name>
  14.     <url-pattern>*.action</url-pattern>
  15.  </servlet-mapping>


最后,让我们看看整个框架图:
 

 
 
上一篇: java设计模式之事务处理    下一篇: java的多进程运行模式分析
  相关文档
在java中应用设计模式之factory method 11-20
两种java容器类list和set分析 11-20
java设计模式之事务处理 11-20
java设计模式之Prototype(原型) 03-14
爪哇语言工厂方法创立性模式介绍(下) 03-14
J2EE相关设计模式讨论 03-14
java对各种文件的操作详解 11-20
企业门户的发展方向 11-20
java的秘密:使用全屏幕模式 11-20
校验值对象——应用visitor模式和反射 11-20
利用observer模式解决组件间通信问题 11-20
技术解析:什么是模式?什么是框架? 11-20
谨慎使用类变量及正确使用单例模式 11-20
单例模式singleton的实现 11-20
J2EE中的设计模式 03-14
用Reflection实现Visitor模式 03-14
在组合模式中实现访问者(visitor)模式 11-20
visitor模式概念——visitor模式进一步 11-20
java设计模式 支撑架构的重要组件 11-20
设计模式之Command 03-14
返回首页 | 关于我们 | J网章程 | JSP空间合租 | 客服中心 | 免责声明 | 常见问题 | 参观机房
本站主机空间代理至厦门市华众网络科技有限公司
《中华人民共和国增值电信业务经营许可证》
编号:闽B2-20050079
@2005-2008福建JSP技术网 版权所有 闽ICP备05000928号
厦门(总部):13616026886 福州:0591-87655121
邮箱:admin@fjjsp.com 站长QQ,点击这里给我发消息