首页 > 学院 > 开发设计 > 正文

自定义MVC

2019-11-09 13:54:28
字体:
来源:转载
供稿:网友
1、定义个servlet(ActionServlet)控制所有的*.do请求   步骤:   a. 创建web项目   b. 创建com.servlet包,创建ActionServlet.java   c. 配置web.xml文件==============================2、在servlet文件中:获得请求路径(request.getRequestURI()),截取到后面的请求名(cname)String url=req.getRequestURI(); //得到你发送的请求路径,就是访问的路径//如:/web2/add.doint start = url.lastIndexOf("/")+1;int end = url.lastIndexOf(".");String cname = url.subString(start, end); //截取add请求名//最后一个“/”起截取================================3、在web-inf下创建一个config.PRoperties文件,保存一个键值对,根据不同的请求得到其对应的Class,同时创建好对应的处理类================================4、在servlet的init()方法中加载配置文件 Properties config=new Properties(); String path=this.getServletContext.getRealPath();//得到其绝对路径 path=path+"/WEB-INF/config.properties"; config.load(new FileInputStream(path));//加载到内存中来 this.getServletContext.setAttribute("config",config); //存入到application中,以便于在处理方法中被调用5、到dopost方法中取出application中的数据,结合前面取到的请求名得到其对应的类名 Properties config=(Properties)this.getServletContext.getAttribute("config"); //先取到application当中的config String className=config.getProperty(cname); //根据请求名 去找到对应的类的名字================================6、将"/WEB-INF/config.properties"存入到web.xml文件中,并通过代码取出 String sname=this.getServletContext().getInitParameter("config");================================7、根据取出来的类名(全路径名),实例化对象//将字符串实例化对象try{Class.forName(classname).newInstance();}================================8、新建一个接口(IAction),声明方法execute();将所有的实现类继承IAction接口 ================================9、将Class.forName返回的对象统一为转换为IAction,再统一的调用execute()方法(多态)  //上面代码要改成:try{  IAction obj=(IAction)Class.forName(classname).newInstance();}================================10、修改接口的方法execute(),让其带参数(request,response),其所有的继承类对应的做修改,保证 能从ActionServlet传送到对应页面================================11、将Action存入到一个池中,步骤:先在init方法中建立一个池(Properties),再在dopost方法中判断,以保证每一个类只会 被实例化一次  有6步:  init()方法中:  a. 创建个池     Properties pool=new Properties();  b. 将池放入application中(上下文)     this.getServletContext().setAttribute("pool",pool);  dopost()方法中:  c. 从application中取池     Properties pool=(Properties)this.getServletContext.getAttribute("pool");     先去池里捞下,判断:<修改代码> 如果池为空,创建池 如果池不为空,直接取出使用 try{    IAction obj=null;     obj=(IAction)pool.get(className);    if(obj==null){ //如果在程序池当中没有该对象 //则实例化一个对象  obj=(IAction)Class.forName(className).newInstance(); //将对象放入到池子中,同时键名指定为类名  pool.put(className, obj);    }    obj.execute(); }     ================================
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表