一、什么是MVC?

MVC全名是Model View Controller
是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码

Model1 jsp+jdbc

Model2 ->MVC

核心思想:各司其职

二、MVC的结构

M
实体域模型(名词)
过程域模型(动词)

V
jsp/ios/android

C
servlet/action

web 做浏览器请求分发
service 调用dao处理项目业务的
dao 操作数据库

:不能跨层调用
:只能出现由上而下的调用

三、自定义MVC工作原理图

mvel调用JAVA自定义方法 自定义mvc_xml


所需要的jar包:

mvel调用JAVA自定义方法 自定义mvc_java_02

四、工具类:

1.ActionModel

package com.huangzhiyao.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来描述action标签
 * @author aojun
 *
 */
public class ActionModel implements Serializable{

	private static final long serialVersionUID = 6145949994701469663L;
	
	private Map<String, ForwardModel> forwardModels = new HashMap<String, ForwardModel>();
	
	private String path;
	
	private String type;
	
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void put(ForwardModel forwardModel){
		forwardModels.put(forwardModel.getName(), forwardModel);
	}
	
	public ForwardModel get(String name){
		return forwardModels.get(name);
	}
}

2.ConfigModel

package com.huangzhiyao.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来描述config标签
 * @author aojun
 *
 */
public class ConfigModel implements Serializable{

	private static final long serialVersionUID = -2334963138078250952L;
	
	private Map<String, ActionModel> actionModels = new HashMap<String, ActionModel>();
	
	public void put(ActionModel actionModel){
		actionModels.put(actionModel.getPath(), actionModel);
	}
	
	public ActionModel get(String name){
		return actionModels.get(name);
	}
}

3.ConfigModelFactory

package com.huangzhiyao.framework;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ConfigModelFactory {
	private ConfigModelFactory() {

	}

	private static ConfigModel configModel = null;

	public static ConfigModel newInstance() throws Exception {
		return newInstance("config.xml");
	}

	/**
	 * 工厂模式创建config建模对象
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static ConfigModel newInstance(String path) throws Exception {
		if (null != configModel) {
			return configModel;
		}

		ConfigModel configModel = new ConfigModel();
		InputStream is = ConfigModelFactory.class.getResourceAsStream(path);
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read(is);
		List<Element> actionEleList = doc.selectNodes("/config/action");
		ActionModel actionModel = null;
		ForwardModel forwardModel = null;
		for (Element actionEle : actionEleList) {
			 actionModel = new ActionModel();
			actionModel.setPath(actionEle.attributeValue("path"));
			actionModel.setType(actionEle.attributeValue("type"));
			List<Element> forwordEleList = actionEle.selectNodes("forward");
			for (Element forwordEle : forwordEleList) {
				forwardModel = new ForwardModel();
				forwardModel.setName(forwordEle.attributeValue("name"));
				forwardModel.setPath(forwordEle.attributeValue("path"));
				forwardModel.setRedirect(forwordEle.attributeValue("redirect"));
				actionModel.put(forwardModel);
			}

			configModel.put(actionModel);
		}

		return configModel;
	}
	
	public static void main(String[] args) {
		try {
			ConfigModel configModel = ConfigModelFactory.newInstance();
			ActionModel actionModel = configModel.get("/loginAction");
			ForwardModel forwardModel = actionModel.get("failed");
			System.out.println(actionModel.getType());
			System.out.println(forwardModel.getPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

4.ForwardModel

package com.huangzhiyao.framework;

import java.io.Serializable;

/**
 * 用来描述forward标签
 * @author aojun
 *
 */
public class ForwardModel implements Serializable {

	private static final long serialVersionUID = -8587690587750366756L;

	private String name;
	private String path;
	private String redirect;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getRedirect() {
		return redirect;
	}

	public void setRedirect(String redirect) {
		this.redirect = redirect;
	}
}

5.mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
	<!--
		config标签:可以包含0~N个action标签
	-->
<config>
	<!--
		action标签:可以饱含0~N个forward标签
		path:以/开头的字符串,并且值必须唯一 非空
		type:字符串,非空
	-->
	<!-- 加法 -->
	<action path="/add" type="web.AddCalAction">
		<!--
			forward标签:没有子标签; 
			name:字符串,同一action标签下的forward标签name值不能相同 ;
			path:以/开头的字符串
			redirect:只能是false|true,允许空,默认值为false
		-->
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
	
		<!-- 减法 -->
	<action path="/del" type="web.DelCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false"></forward>
	</action>
	<!-- 乘法 -->
	<action path="/x" type="web.XCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false"></forward>
	</action>
	<!-- 除法 -->
	<action path="/c" type="web.CCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false"></forward>
	</action>	
</config>

将Action的信息配置到xml(反射实例化)
index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function  doSub(v) {
	if(v == 1){
		calform.action = "${pageContext.request.contextPath}/add.action";
	}else if(v == 2){
		calform.action = "${pageContext.request.contextPath}/del.action";
	}else if(v == 3){
		calform.action = "${pageContext.request.contextPath}/x.action";
	}else if(v == 4){
		calform.action = "${pageContext.request.contextPath}/c.action";
	}
	calform.submit();
}
</script>
<body>
<form id="calform" action="" method="post">
		num1: <input type="text" name="num1"><br>
		num2: <input type="text" name="num2"><br>
		<button onclick="doSub(1)">+</button>
		<button onclick="doSub(2)">-</button>
		<button onclick="doSub(3)">*</button>
		<button onclick="doSub(4)">/</button>
</form>
</body>
</html>

中央控制器 DispatcherServlet

package com.huangzhiyao.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import com.huangzhiyao.web.AddCalAction;
import com.huangzhiyao.web.CCalAction;
import com.huangzhiyao.web.DelCalAction;
import com.huangzhiyao.web.XCalAction;
/**
 * 中央控制器
 * 作用:
 * 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
 * 
 * 五步增强:
 * 1、对存放子控制器action容器的增强(类似web.xml实例化 反射)
 * 	为什么:原来为了完成业务需求,需要不断修改框架代码,这样的设计不合理
 * 	处理方式:参照web.xml的设计方法,来完成中央控制器来管理子控制器的动态配置
 * 
 * @author aojun
 *
 */
public class DispatcherServlet extends HttpServlet {


	private static final long serialVersionUID = -5751428465348681594L;
	//增强前:
//	private Map<String, Action> actionMap = new HashMap<String, Action>();
//	
//	public void init() {
//		actionMap.put("/add", new AddCalAction());
//		actionMap.put("/del", new DelCalAction());
//		actionMap.put("/x", new XCalAction());
//		actionMap.put("/c", new CCalAction());
//	}
	//增强后:
	private ConfigModel configModel = null;
	
	public void init() {
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String url = req.getRequestURI();
			url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));//截取对应的网址
			/**
			 * 增强前:
			 */
//			AddCalAction action = (AddCalAction) actionMap.get(url);
//			Action a = action;
		//	↓↓
//			Action action = actionMap.get(url);//通过截取的地址找到对应的类
//			try {
//				action.execute(req, resp);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}//然后实现方法
			/**
			 * 增强后:
			 * 
			 */
			ActionModel actionModel = configModel.get(url);
			try {
				//拿到类对象并实例化
			Action action =	(Action) Class.forName(actionModel.getType()).newInstance();
				action.execute(req, resp);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
	}	
}

子控制器 接口: Action

package com.huangzhiyao.framework;

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

/**
 * 子控制器:
 * 作用:
 * 具体处理用户请求的类(实现了Action接口的类)
 * @author aojun
 *
 */
public interface Action {
	String execute(HttpServletRequest req,HttpServletResponse resp) throws Exception, Exception;
}

package com.huangzhiyao.web;

import java.io.IOException;

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

import entity.Cal;
import songwanxi_mvc.framework.Action;

public class AddCalAction implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2());
		req.getRequestDispatcher("/rs.jsp").forward(req, resp);
		return null;
	}

}

package com.huangzhiyao.web;

import java.io.IOException;

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

import entity.Cal;
import songwanxi_mvc.framework.Action;

public class DelCalAction implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
		req.getRequestDispatcher("/rs.jsp").forward(req, resp);
		return null;
	}
}

package com.huangzhiyao.web;

import java.io.IOException;

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

import entity.Cal;
import songwanxi_mvc.framework.Action;

public class XCalAction implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
		req.getRequestDispatcher("/rs.jsp").forward(req, resp);
		return null;
	}
}

package com.huangzhiyao.web;

import java.io.IOException;
import java.math.BigDecimal;

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

import entity.Cal;
import songwanxi_mvc.framework.Action;

public class CCalAction implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		BigDecimal b1 = new BigDecimal(cal.getNum1());
		BigDecimal b2 = new BigDecimal(cal.getNum2());
		req.setAttribute("rs", b1.divide(b2));
		req.getRequestDispatcher("/rs.jsp").forward(req, resp);
		return null;
	}
}

运行测试:

mvel调用JAVA自定义方法 自定义mvc_html_03


结果:

mvel调用JAVA自定义方法 自定义mvc_java_04

通过结果码控制页面的跳转
修改子控制器页面:

AddCalAction:

package com.huangzhiyao.web;

import java.io.IOException;

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

import com.huangzhiyao.entity.Cal;
import com.huangzhiyao.framework.Action;

public class AddCalAction implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(num1)+Integer.valueOf(num2));
		return "rs";
	}
}

中央控制器

package com.huangzhiyao.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import com.huangzhiyao.web.AddCalAction;
import com.huangzhiyao.web.CCalAction;
import com.huangzhiyao.web.DelCalAction;
import com.huangzhiyao.web.XCalAction;
/**
 * 中央控制器
 * 作用:
 * 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
 * 
 * 五步增强:
 * 1、对存放子控制器action容器的增强(类似web.xml实例化 反射)
 * 	为什么:原来为了完成业务需求,需要不断修改框架代码,这样的设计不合理
 * 	处理方式:参照web.xml的设计方法,来完成中央控制器来管理子控制器的动态配置
 * 
 * 2、处理结果码的跳转形式
 * 	达到简化代码的作用
 * 
 * 
 * @author aojun
 *
 */
public class DispatcherServlet extends HttpServlet {


	private static final long serialVersionUID = -5751428465348681594L;
	//增强前:
//	private Map<String, Action> actionMap = new HashMap<String, Action>();
//	
//	public void init() {
//		actionMap.put("/add", new AddCalAction());
//		actionMap.put("/del", new DelCalAction());
//		actionMap.put("/x", new XCalAction());
//		actionMap.put("/c", new CCalAction());
//	}
	//增强后:
	private ConfigModel configModel = null;
	
	public void init() {
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String url = req.getRequestURI();
			url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));//截取对应的网址
			/**
			 * 增强前:
			 */
//			AddCalAction action = (AddCalAction) actionMap.get(url);
//			Action a = action;
		//	↓↓
//			Action action = actionMap.get(url);//通过截取的地址找到对应的类
//			try {
//				action.execute(req, resp);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}//然后实现方法
			/**
			 * 增强后:
			 * 
			 */
			ActionModel actionModel = configModel.get(url);
			try {
				if(actionModel == null) {//当没有对应的子控制器时 提示
					throw new RuntimeException("没有配置指定的子控制器");
				}
				
				//拿到类对象并实例化
			Action action =	(Action) Class.forName(actionModel.getType()).newInstance();
			String code = action.execute(req, resp); //code 结果码
				ForwardModel forwardModel = actionModel.get(code);
				if("false".equals(forwardModel.getRedirect())) {//判断是转发还是重定向
					req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
				}else {
					//会默认缺省项目名 要补齐项目名
					resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
	}
}

将一组相关的操作放到一个Action中(反射调用方法)

新建ActionSupport:

packagecom.huangzhiyao.framework;

import java.lang.reflect.Method;

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

/**
 * 增强版子控制器
 * 	作用:为了将一组操作放到一个子控制器中完成
 * @author aojun
 *
 */
public class ActionSupport implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		//从前台传递需要调用的方法名到后台,实现动态方法调用
		String methodName = req.getParameter("methodName");
		String code=null;
		//获取ClaAction的实例 根据传过来的方法名调用对应的方法
		Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
		//打开权限
		m.setAccessible(true);
		//返回值
		code = (String) m.invoke(this, req,resp);
		return code;
	}
}

新建ClaAction

package com.huangzhiyao.web;

import java.math.BigDecimal;

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

import entity.Cal;
import com.huangzhiyao..framework.ActionSupport;

public class ClaAction extends ActionSupport{
	//add
	public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	//del
	public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	//c
	public String cc(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		BigDecimal b1 = new BigDecimal(cal.getNum1());
		BigDecimal b2 = new BigDecimal(cal.getNum2());
		req.setAttribute("rs", b1.divide(b2));
		return "rs";
	}
	//xc
	public String xc(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal();
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
		return "rs";
	}
}

修改mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
	<!--
		config标签:可以包含0~N个action标签
	-->
<config>
	<!--
		action标签:可以饱含0~N个forward标签
		path:以/开头的字符串,并且值必须唯一 非空
		type:字符串,非空
	-->
	<!-- * -->
	<action path="/cal" type="web.ClaAction">
		<!--
			forward标签:没有子标签; 
			name:字符串,同一action标签下的forward标签name值不能相同 ;
			path:以/开头的字符串
			redirect:只能是false|true,允许空,默认值为false
		-->
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>	
</config>

测试:index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function  doSub(v) {
	if(v == 1){
		calform.action = "${pageContext.request.contextPath}/cal.action?methodName=add";
	}else if(v == 2){
		calform.action = "${pageContext.request.contextPath}/cal.action?methodName=del";
	}else if(v == 3){
		calform.action = "${pageContext.request.contextPath}/cal.action?methodName=xc";
	}else if(v == 4){
		calform.action = "${pageContext.request.contextPath}/cal.action?methodName=cc";
	}
	calform.submit();
}
</script>
<body>
<form id="calform" action="" method="post">
		num1: <input type="text" name="num1"><br>
		num2: <input type="text" name="num2"><br>
		<button onclick="doSub(1)">+</button>
		<button onclick="doSub(2)">-</button>
		<button onclick="doSub(3)">*</button>
		<button onclick="doSub(4)">/</button>
</form>
</body>
</html>

利用ModelDriven接口对Java对象进行赋值(反射读写方法)
ModelDriven

package com.huangzhiyao.framework;
/**
 * 模型驱动接口:
 *    作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
 *    
 * @author aojun
 *
 * @param <T>
 */
public interface ModeDriven<T> {
 T getModel();
}
② 修改ClaAction类 实现ModelDriven
package web;

import java.math.BigDecimal;

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

import entity.Cal;
import com.huangzhiyao..framework.ActionSupport;
import com.huangzhiyao..framework.ModeDriven;

public class ClaAction extends ActionSupport implements ModeDriven<Cal>{
	private Cal cal = new Cal();
	
	//add
	public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	//del
	public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	//c
	public String cc(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		BigDecimal b1 = new BigDecimal(cal.getNum1());
		BigDecimal b2 = new BigDecimal(cal.getNum2());
		req.setAttribute("rs", b1.divide(b2));
		return "rs";
	}
	//xc
	public String xc(HttpServletRequest req, HttpServletResponse resp) throws Exception, Exception {
		req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	@Override
	public Cal getModel() {
		// TODO Auto-generated method stub
		return cal;
	}	
}

中央控制器

package com.huangzhiyao.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.huangzhiyao.web.AddCalAction;
import com.huangzhiyao.web.CCalAction;
import com.huangzhiyao.web.DelCalAction;
import com.huangzhiyao.web.XCalAction;
/**
 * 中央控制器
 * 作用:
 * 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
 * 
 * 五步增强:
 * 1、对存放子控制器action容器的增强(类似web.xml实例化 反射)
 * 	为什么:原来为了完成业务需求,需要不断修改框架代码,这样的设计不合理
 * 	处理方式:参照web.xml的设计方法,来完成中央控制器来管理子控制器的动态配置
 * 
 * 2、处理结果码的跳转形式
 * 	达到简化代码的作用
 * 
 * 3、将一组操作放到一个子控制器去完成
 * 
 * 4、处理jsp传递到后台的参数封装
 * 
 * 
 * 
 * @author aojun
 *
 */
public class DispatcherServlet extends HttpServlet {


	private static final long serialVersionUID = -5751428465348681594L;
	//增强前:
//	private Map<String, Action> actionMap = new HashMap<String, Action>();
//	
//	public void init() {
//		actionMap.put("/add", new AddCalAction());
//		actionMap.put("/del", new DelCalAction());
//		actionMap.put("/x", new XCalAction());
//		actionMap.put("/c", new CCalAction());
//	}
	//增强后:
	private ConfigModel configModel = null;
	
	public void init() {
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String url = req.getRequestURI();
			url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));//截取对应的网址
			/**
			 * 增强前:
			 */
//			AddCalAction action = (AddCalAction) actionMap.get(url);
//			Action a = action;
		//	↓↓
//			Action action = actionMap.get(url);//通过截取的地址找到对应的类
//			try {
//				action.execute(req, resp);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}//然后实现方法
			/**
			 * 增强后:
			 * 
			 */
			ActionModel actionModel = configModel.get(url);
			try {
				if(actionModel == null) {//当没有对应的子控制器时 提示
					throw new RuntimeException("没有配置指定的子控制器");
				}
				
				//拿到类对象(Cal)并实例化
			Action action =	(Action) Class.forName(actionModel.getType()).newInstance();
			if(action instanceof ModeDriven) {//如果action实现了ModeDriven就能向上转型
				ModeDriven modeDriven = (ModeDriven) action; //==cal
				Object model = modeDriven.getModel();
				//给model赋值了。那么意味着在调用add/del方法时 cal就是有值的
				//把Map里的键值对封装到实体类中去(赋值)
				BeanUtils.populate(model, req.getParameterMap());
			}
			
			
			
			String code = action.execute(req, resp); //code 结果码
				ForwardModel forwardModel = actionModel.get(code);
				if("false".equals(forwardModel.getRedirect())) {//判断是转发还是重定向
					req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
				}else {
					//会默认缺省项目名 要补齐项目名
					resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
	}	
}

解决框架配置文件重名冲突问题
中央配置器

package com.huangzhiyao.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import  com.huangzhiyao.web.AddCalAction;
import  com.huangzhiyao.web.CCalAction;
import  com.huangzhiyao.web.DelCalAction;
import  com.huangzhiyao.web.XCalAction;
/**
 * 中央控制器
 * 作用:
 * 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
 * 
 * 五步增强:
 * 1、对存放子控制器action容器的增强(类似web.xml实例化 反射)
 * 	为什么:原来为了完成业务需求,需要不断修改框架代码,这样的设计不合理
 * 	处理方式:参照web.xml的设计方法,来完成中央控制器来管理子控制器的动态配置
 * 
 * 2、处理结果码的跳转形式
 * 	达到简化代码的作用
 * 
 * 3、将一组操作放到一个子控制器去完成
 * 
 * 4、处理jsp传递到后台的参数封装
 * 
 * 5、解决框架配置文件重名冲突问题
 * 
 * @author aojun
 *
 */
public class DispatcherServlet extends HttpServlet {


	private static final long serialVersionUID = -5751428465348681594L;
	//增强前:
//	private Map<String, Action> actionMap = new HashMap<String, Action>();
//	
//	public void init() {
//		actionMap.put("/add", new AddCalAction());
//		actionMap.put("/del", new DelCalAction());
//		actionMap.put("/x", new XCalAction());
//		actionMap.put("/c", new CCalAction());
//	}
	//增强后:
	private ConfigModel configModel = null;
	
	public void init() {
		try {
			//xml重名冲突解决方法
			String mvcXmlLocation = ""; //mvc的文件位置
			mvcXmlLocation = this.getInitParameter("mvcXmlLocation");
			if(null == mvcXmlLocation || "".equals(mvcXmlLocation)) {//当没有配置时,使用默认的
				mvcXmlLocation = "mvc.xml";
			}
			
			System.out.println("mvcXmlLocation:"+mvcXmlLocation);
			
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String url = req.getRequestURI();
			url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));//截取对应的网址
			/**
			 * 增强前:
			 */
//			AddCalAction action = (AddCalAction) actionMap.get(url);
//			Action a = action;
		//	↓↓
//			Action action = actionMap.get(url);//通过截取的地址找到对应的类
//			try {
//				action.execute(req, resp);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}//然后实现方法
			/**
			 * 增强后:
			 * 
			 */
			ActionModel actionModel = configModel.get(url);
			try {
				if(actionModel == null) {//当没有对应的子控制器时 提示
					throw new RuntimeException("没有配置指定的子控制器");
				}
				
				//拿到类对象(Cal)并实例化
			Action action =	(Action) Class.forName(actionModel.getType()).newInstance();
			if(action instanceof ModeDriven) {//如果action实现了ModeDriven就能向上转型
				ModeDriven modeDriven = (ModeDriven) action; //==cal
				Object model = modeDriven.getModel();
				//给model赋值了。那么意味着在调用add/del方法时 cal就是有值的
				//把Map里的键值对封装到实体类中去(赋值)
				BeanUtils.populate(model, req.getParameterMap());
			}
			
			
			
			String code = action.execute(req, resp); //code 结果码
				ForwardModel forwardModel = actionModel.get(code);
				if("false".equals(forwardModel.getRedirect())) {//判断是转发还是重定向
					req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
				}else {
					//会默认缺省项目名 要补齐项目名
					resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
	}	
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>songwanxi_mvc</display-name>
 	<servlet>
 	<servlet-name>dispatcherServlet</servlet-name>
 	<servlet-class>songwanxi_mvc.framework.DispatcherServlet</servlet-class>
 	<!-- 当有同名的xml文件时,可以采用 ,没有重名时就注销 使用默认的 -->
 	<init-param>
 	<param-name>mvcXmlLocation</param-name>
 	<param-value>/song.xml</param-value>
 	</init-param>
 	</servlet>
 	<servlet-mapping>
 	<servlet-name>dispatcherServlet</servlet-name>
 	<url-pattern>*.action</url-pattern>
 	</servlet-mapping>
</web-app>

感谢观看