自己实现的MVC框架源代码

这是我在研究和学习了struts后自己实现的一套MVC框架,主要实现的是控制层。开发工具是eclipse,连接的是sql数据库。

编写思想:

接近于struts思想,用servlet来分发和跳转,当从客户端发出请求后都由这个actionServler来控制,在调用各个java类来实现具体实现。

定义的web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>com.king.controller.ActionServlet</servlet-class>
    <init-param>
     <param-name>config</param-name>
     <param-value>/WEB-INF/mvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
   <servlet>
    <servlet-name>Config</servlet-name>
    <servlet-class>com.king.DB.Config</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>InitDBConfig</servlet-name>
    <servlet-class>com.king.init.InitDBConfig</servlet-class>
    <init-param>
     <param-name>driverName</param-name>
     <param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
    </init-param>
    <init-param>
     <param-name>URL</param-name>
     <param-value>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs</param-value>
    </init-param>
   <init-param>
     <param-name>userName</param-name>
     <param-value>sa</param-value>
   </init-param>
    <init-param>
     <param-name>password</param-name>
     <param-value></param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

自定义的mvc.config.xml配置信息:

<?xml version="1.0" encoding="UTF-8"?>
<mvc>
   <action path="/select"  class="com.king.action.UsersAction" />
   <action path="/Login"   class="com.king.action.UsersAction" method="Login"/>
   <action path="/update"  class="com.king.action.UsersAction" method="update"/>
   <action path="/selectUpdate"  class="com.king.action.UsersAction" method="selectUpdate"/>
   <action path="/delect"  class="com.king.action.UsersAction" method="delect"/>
   <action path="/insert"  class="com.king.action.UsersAction" method="insert"/>
   <action path="/selectAll"  class="com.king.action.UsersAction" method="selectAll"/>
</mvc>

定义的DB数据层:

package com.king.DB;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;

public class DBManager {
 
  /** 表示与数据库的连接 */
  private static Connection con;
 
  /** 表示 */
  private static Statement sta;
 
  /** 表示查询的结果集 */
  private static ResultSet rs;
 
  /**
  * 用来执行insert update delete操作
  * @param sql
  * @return sql语句影响的行数
  */
 public static int executeUpdate(String sql) {
  int rows = 0;
  try {
   System.out.println(sql);
   Class.forName(Config.driverName);
   con = DriverManager.getConnection(Config.URL, Config.userName, Config.password);
   sta = con.createStatement();
   rows = sta.executeUpdate(sql);
  } catch (ClassNotFoundException e) {
   System.out.println("驱动程序没有找到");
   e.printStackTrace();
  } catch (SQLException e) {
   System.out.println("发生了SQL异常");
   e.printStackTrace();
  }
  return rows;
 }
 /**
  * 用来执行select语句
  * @param sql
  * @return 结果集
  */
 public static ResultSet executeQuery(String sql) {
  try {
   Class.forName(Config.driverName);
   con = DriverManager.getConnection(Config.URL, Config.userName,Config.password);
   sta = con.createStatement();
   rs = sta.executeQuery(sql);
  } catch (ClassNotFoundException e) {
   System.out.println("驱动程序没有找到");
   e.printStackTrace();
  } catch (SQLException e) {
   System.out.println("发生了SQL异常");
   e.printStackTrace();
  }
  return rs;
 }
 /**
  * 用来关闭数据库连接
  */
 public void closeCon() {
  try {
   if (rs != null) {
    rs.close();
    rs = null;
   }
   if (sta != null) {
    sta.close();
    sta = null;
   }
   if (con != null) {
    con.close();
    con = null;
   }
  } catch (SQLException e) {
   System.out.println("发生了SQL异常");
   e.printStackTrace();
  }
 }
}

DB数据层辅助类:Config类

package com.king.DB;

public class Config {
   /** 加载驱动字符串 */
   public static String driverName ;//= "com.microsoft.jdbc.sqlserver.SQLServerDriver";
   /** 存储用户名 */
   public static String userName;// = "sa";
   /** 存储密码 */
   public static String password;// = "";
   /** 表示 SQLServer 的路径*/
   public static String URL;// = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs";
   /** 存储每页显示的条数 */
  // public static String pageno;
}

DB数据层辅助类:InitDBConfig类

package com.king.init;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.king.DB.Config;

@SuppressWarnings("serial")
public class InitDBConfig extends HttpServlet {
 
 public void init(ServletConfig config)throws ServletException {
  Config.driverName = config.getInitParameter("driverName");
  Config.userName = config.getInitParameter("userName");
  Config.password = config.getInitParameter("password");
  Config.URL = config.getInitParameter("URL");
  
  System.out.println("-------driverName="+ Config.driverName+"---------");
  System.out.println("-------URL="+ Config.URL+"---------");
  System.out.println("-------userName="+ Config.userName+"---------");
  System.out.println("-------password="+ Config.password+"---------");
 }
}

五个控制类:

1.定义的Action接口:

package com.king.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public interface Action {
 public ActionForward execute(HttpServletRequest request, HttpServletResponse response);
}

2.定义的ActionServlet控制类:

package com.king.controller;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ActionServlet extends HttpServlet {

 public ActionServlet() {
  super();
 }

 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  this.doProcessor(request,response);
 }
 
 private void doProcessor(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   //获取从JSP的请求过来的路径,从放到变量servletPath中
   String servletPath = request.getServletPath();
   System.out.println(servletPath);
   try {
    //判断所请求的路径是否为.do后缀。如果路径是否正确继续,错误截取字符串后三位
    if (servletPath.indexOf(".") != -1) {
     //substring截去字符串,从0开始,到后三位
     servletPath = servletPath.substring(0,servletPath.indexOf("."));
     System.out.println(servletPath);
    }
    //给ActionMapping类中的Hashtable集合中的getAction方法传个键(路径)得到所对应的值,就是程序启动从xml描述信息中得到的加载,所得到描述信息属性所对应的对象
    ActionConfig action = ActionMapping.getAction(servletPath);
//    System.out.println(action.toString());
    //判断返回的值是否为空,
    if (action == null) {
     //返回一个404错误,和提示信息
     response.sendError(404, "action 值没有找到!!!!");
     return;
    }
    //--------------------------------反射--------------------------------------------//
    //获取ActionConfig封装类中所封装的相应对象(也就是类包中的类,也是对象吗?),target目标
    Object target = action.getAction();
//    System.out.println(target.toString());
    //获取ActionConfig封装类中所封装的相对应的这个Class对象,target是个对象,是描述类的对象
    Class targetclass = target.getClass();
//    System.out.println(targetclass.toString());
    //获取这个Class对象中的方法名称
    String methodName = action.getMethod();
//    System.out.println(methodName.toString());
    //获取描述类的对象,放到Class的类数组里,参数是用Class的对象点class获取的是Class的对象
    Class[] parameterType = new Class[] {HttpServletRequest.class, HttpServletResponse.class };
    //通过methodName方法名称,获取argsType类里的方法
    Method method = targetclass.getMethod(methodName, parameterType);
//    System.out.println(method.toString());
    //-------------------------------------反射结束------------------------------------------------------//
    
    //Object target 指Method对象method,是target(目标)的方法,new Object[]{request,response} 执行method方法需要哪些参数?
    //Return 返回结果是方法method调用后的结果(result)
    Object result = method.invoke(target, new Object[] { request,response });
//    System.out.println(result.toString());
    
    //Action接口实现对象点execute方法把客户的依次请求和响应对象传给实现类,实现类通过request点来得到信息,
    //调用DAO执行数据库,返回一个ActionForward对象,
    ActionForward afw = (ActionForward) result;
//    System.out.println(afw.toString());
    //判断ActionForward所的到的值是否为空,是否长度是为0,ActionForward应用所指向的内存是否为空
    if (afw != null && afw.getPath() != null && afw.getPath().length() != 0) {
     if (afw.isDirect()) {
      //请求转发
      request.getRequestDispatcher(afw.getPath()).forward(
        request, response);
     } else {
      //重定向
      response.sendRedirect(request.getContextPath()
        + afw.getPath());
     }
    }
   } catch (Exception e) {
    e.printStackTrace();
    response.sendError(500,e.getMessage());
   }   
  }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  this.doProcessor(request,response);
 }

 public void init() throws ServletException {
  //获取当前系统程序路径,Real真实的,getRealPath()真实的路径,getServletContext()servlet上下文
  String realPath = this.getServletContext().getRealPath(".");
  //获取当前程序xml配置信息中的config值,getServletConfig()Servlet的配置信息,getInitParameter("config")init中config的配置信息
  String xmlPath = this.getServletConfig().getInitParameter("config");
  //调用ActionMapping类中的loadMapping方法,传一个自定义xml的完全存放地址
  ActionMapping.loadMapping(realPath+xmlPath);
  //初始化WEB应用程序
  //ActionMapping.putAction("/LoginAction", new LoginAction());
  System.out.println("数据初始化成功!!!!!!!!!!!!!!!");
 }

}
3.定义的辅助类ActionMapping:

package com.king.controller;

import java.util.List;
import java.util.Hashtable;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 *用来与业务层的连接,把业务层的返回结果存放到Hashtable
 */
public class ActionMapping {
 //定义一个静态的Hashtable来与数据层进行连通,同过数据层传过来的path,action对性存放在Hashtable中
 static Hashtable<String,ActionConfig> hashtable 
      = new Hashtable<String, ActionConfig>();
 /**
  *@param path 路径
  *@param action 接口子类实现对象
  */
 public static void putAction(String path,ActionConfig action){
  hashtable.put(path,action);
 }
 /**
  *@param path 路径,也是Hashtable中的键
  *@return 返回通过路径取出Hashtable的值
  */
 public static ActionConfig getAction(String path) {
  return hashtable.get(path);
 }
 
 /**
  *@param filepath 路径,自定义xml的完全存放地址
  */
 public static void loadMapping(String filepath) {
  //SAXBuilder输出类(SAXBuilder,DOMBuilder,ResultSetBuilder,org.JDOM.),一般用于文档的创建工作,parser 剖析器
  SAXBuilder parser  = new SAXBuilder();
  try {
   //通过参数路径filepath来解析mvc-config.xml,Document 文件,build格式,返回Document(文件)类对象
   Document doc = parser .build(filepath);
   //获取描述信息mvc-config.xml的根元素,Root根,Element 元素,返回Element(元素)类对象,也是org.JDOM这个包的一个类,是解析xml文档后用到的数据类型
   Element root = doc.getRootElement();//获得根元素element

   //获取子节点,Children子类,
   List list = root.getChildren();//注意此处取出的是root节点下面的一层的Element集合
   //便利这个描述信息的所有元素
   for (Object object : list) {
    //
    Element e = (Element)object;
    //获取mvc-config.xmlmvc-config.xml描述信息的子元素属性path值
    String path = e.getAttributeValue("path");
    //获取mvc-config.xmlmvc-config.xml描述信息的子元素属性class值
    String clazz = e.getAttributeValue("class");
    //获取mvc-config.xmlmvc-config.xml描述信息的子元素属性method值
    String method = e.getAttributeValue("method");
    
    //反射,Class.forName(clazz).newInstance()获取clazz所对应的class对象
    Object obj = Class.forName(clazz).newInstance();
    //创建ActionConfig类,此类封装了mvc-config.xmlmvc-config.xml描述信息的两个属性action和method,在创建时把这个对象传个对象属性
    ActionConfig action = new ActionConfig(obj);
    //判断mvc-config.xmlmvc-config.xml描述信息字节点中属性中有没有method属性,有就把他的值放到ActionConfig这个封装类中的setMethod方法中
    if(method!= null && method.length()!=0){
     action.setMethod(method);
    }else{
     //当没有时就个他的默认值
     method = "execute";
    }
    //给ActionMapping这个类中封装Hashtable中的方法putAction传值,此方法用来往Hashtable中放值
    ActionMapping.putAction(path, action);
    System.out.println(clazz+"的"+method+"方法正在初始化......");
    
   }
  } catch (Exception e) {
   e.printStackTrace();
  }  
  
  
  
 }
}
4.定义的辅助类ActionForward类:

apackage com.king.controller;

public class ActionForward {
 String path;
 boolean isDirect =false;
 
 public ActionForward(boolean isDirect) {
  super();
  this.isDirect = isDirect;
 }

 public ActionForward() {
  super();
 }
 
 public ActionForward(String path, boolean isDirect) {
  super();
  this.path = path;
  this.isDirect = isDirect;
 }
 public ActionForward(String path) {
  super();
  this.path = path;
 }
 public boolean isDirect() {
  return isDirect;
 }
 public void setDirect(boolean isDirect) {
  this.isDirect = isDirect;
 }
 public String getPath() {
  return path;
 }
 public void setPath(String path) {
  this.path = path;
 }
}
5.定义的辅助类ActionConfig 类:

package com.king.controller;

/**
 * 封装mvc-config.xmlmvc-config.xml描述信息两个属性action,method,
 */
public class ActionConfig {
 Object action;//表示所包含的全路径名
 String method ="execute";//表示当没有method属性值时默认值为execute方法
 
 public ActionConfig() {
  super();
 }
 
 public ActionConfig(Object action) {
  super();
  this.action = action;
 }

 public ActionConfig(Object action, String method) {
  this(action);
  this.method = method;
 }
 public Object getAction() {
  return action;
 }
 public void setAction(Object action) {
  this.action = action;
 }
 public String getMethod() {
  return method;
 }
 public void setMethod(String method) {
  this.method = method;
 }
}
VO:

package com.king.entity;

/**
 * @author Administrator
 *
 */
public class EmployeeEntity {
 int empid;
 String empname;
 String emppwd;
 int empsex;
 String empdegree;
 char deleteFelg = '1';
 public String getEmpdegree() {
  return empdegree;
 }
 public void setEmpdegree(String empdegree) {
  this.empdegree = empdegree;
 }
 public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 public String getEmpname() {
  return empname;
 }
 public void setEmpname(String empname) {
  this.empname = empname;
 }
 public String getEmppwd() {
  return emppwd;
 }
 public void setEmppwd(String emppwd) {
  this.emppwd = emppwd;
 }
 public int getEmpsex() {
  return empsex;
 }
 public void setEmpsex(int empsex) {
  this.empsex = empsex;
 }
 public char getDeleteFelg() {
  return deleteFelg;
 }
 public void setDeleteFelg(char deleteFelg) {
  this.deleteFelg = deleteFelg;
 }
 
}

在实现时可能实现不够,还望指教和提出意见和建议!!!!!!!

转载于:https://my.oschina.net/chen106106/blog/41544

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值