自定义mvc框架(上)

1.什么是mvc

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

Model1 jsp+jdbc
Model2 ->MVC

核心思想:各司其职

2.mvc结构

V     
         jsp/ios/android
C     
         servlet/action
M  
         实体域模型(名词)
         过程域模型(动词)  
 
jsp
	<%
	
		
	%>

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

  注意1:不能跨层调用
         2:只能出现由上而下的调用

现今开发
	实体类、dao、web
		AddBookServlet
		DelBookServlet
		。。。。。。
		
	web.xml
		AddBookServlet
		DelBookServlet
		。。。。。。
		
		
....>
	BookServlet
	web.xml
		BookServlet
		String methodName = req.getParamater("methodName");
		String methodName = req.getParamater("bname");
		String methodName = req.getParamater("pice");
		String methodName = req.getParamater("type");
		........
		Book b = new Book();
		b.set()
		......
		
		if("add".equals(methodName)){
			add(req,resp);
		}
		
		重定向、转发
		req.getResquestDispather("xxx.jsp").forward(req,resp);
		resp.sendRedirect();
		
	jsp--->methodName=add/del/....

前一种方式有一种方式有什么不好呢?
1、BookServlet中的if语句判断非常多
2、省去jsp传递到后台封装成对象的过程
3、省去结果集的处理

>中央控制器
子控制器

看图分析自定义mvc解决的问题

在这里插入图片描述

3. 自定义MVC工作原理图

主控制动态调用子控制器调用完成具体的业务逻辑
(火车、控制台、车轨)
请求、主控制器、子控制器

业务编码:子控制器
自定义mvc的范畴:主控制器

看图分析自定义mvc原理

也是源自于生活,java核心思想是面向对象,描述现实生活中的事物。
如下也是从现实事物中启发得来东西。
在这里插入图片描述

小结:
主控制器:查看是否有对应的子控制器来处理用户请求,如果就调用子控制器来处理请求
;没有就报错,就处理不了请求
子控制器:就是处理用户请求用的

4.通过XML对自定义mvc框架进行增强

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

代码演示
需要用到的jar包:
在这里插入图片描述
jar包分享:

链接:https://pan.baidu.com/s/13jBTCFJdC4dzX_tlCL2aRQ
提取码:jn5s

建模:

package com.myy.framework;

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

/**
 * 用来描述action标签
 * @author myy
 *
 */
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);
	}
	
}

package com.myy.framework;

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

/**
 * 用来描述config标签
 * @author myy
 *
 */
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);
	}
	
}

package com.myy.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("mvc.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();
		}
	}
}

package com.myy.framework;
import java.io.Serializable;

/**
 * 用来描述forward标签
 * @author myy
 *
 */
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;
	}

}

转发请求DispatecherServlet:

package com.myy.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.myy.web.AddCalAction;
import com.myy.web.DelCalAction;

/**
 * 中央控制器
 * 作用:
 *  接收用户请求,通过用户请求的url寻找指定的自控制器去处理业务
 *  
 *  1.对存放自控制器action容器的增强
 *  why:原来为了完成业务需求,需求不断修改框架的代码,这样设计是不合理的
 *  处理方式:参照web.xml的设计方法,来完成中央控制器管理控制器的动态配置
 * @author myy
 *
 */
public class DispatecherServlet extends HttpServlet {

	private static final long serialVersionUID = 7187494273786588096L;

//	private Map<String,Action> actionMap = new HashMap<String,Action>();
	private ConfigModel configModel = null;
	
	
	public void init() {
//		http://localhost:8080/T237_mvc/cal_add.action
//		/T237_mvc/cal_add.action
//		actionMap.put("/cal_add", new AddCalAction());
//		actionMap.put("/cal_del", new DelCalAction());
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	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 action = actionMap.get(url);
//        action.execute(req, resp);
        ActionModel actionModel = configModel.get(url);
        actionModel.getType();
        try {
        	  //反射实例化
			Action action = (Action) Class.forName(actionModel.getType()).newInstance();
			action.execute(req, resp);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
        
	}
}

接口Action:

package com.myy.framework;

import java.io.IOException;

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

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

新建mvc.xml

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<action path="/cal_add" type="com.myy.web.AddCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
	<action path="/cal_del" type="com.myy.web.DelCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
</config>

加法AddCalAction:

package com.myy.web;

import java.io.IOException;

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

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

public class AddCalAction implements Action{

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

}

减法DelCalAction:
package com.myy.web;

import java.io.IOException;

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

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

public class DelCalAction implements Action{

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

}
文件cal.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>
<script type="text/javascript">
 function doSub(v) {
	if(v==1){
		calForm.action = "${pageContext.request.contextPath }/cal_add.action";
	}else if(v==2){
		calForm.action = "${pageContext.request.contextPath }/cal_del.action";
	}
	calForm.submit();
}


</script>
</head>
<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>

测试结果rs.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>
<body>

结果:${rs}
</body>
</html>

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.2 通过结果码控制页面的跳转

处理结果码的跳转形式
达到简化代码的目的

当AddCalAction和DelCalAction没有如下代码还能跳页面,则做到简化代码

 req.getRequestDispatcher("/rs.jsp").forward(req, resp);	
 或
 resp.sendRedirect("/rs.jsp");

换另一种方式加和减法的跳转

package com.myy.web;

import java.io.IOException;

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

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

public class AddCalAction implements Action{

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

}

package com.myy.web;

import java.io.IOException;

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

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

public class DelCalAction implements Action{

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

}

对DispatecherServlet进行修改:

package com.myy.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.myy.web.AddCalAction;
import com.myy.web.DelCalAction;

/**
 * 中央控制器
 * 作用:
 *  接收用户请求,通过用户请求的url寻找指定的自控制器去处理业务
 *  
 *  1.对存放自控制器action容器的增强
 *  why:原来为了完成业务需求,需求不断修改框架的代码,这样设计是不合理的
 *  处理方式:参照web.xml的设计方法,来完成中央控制器管理控制器的动态配置
 * 
 * 2.处理结果码的跳转形式
 *   达到简化代码的目的
 * @author myy
 *
 */
public class DispatecherServlet extends HttpServlet {

	private static final long serialVersionUID = 7187494273786588096L;

//	private Map<String,Action> actionMap = new HashMap<String,Action>();
	private ConfigModel configModel = null;
	
	
	public void init() {
//		http://localhost:8080/T237_mvc/cal_add.action
//		/T237_mvc/cal_add.action
//		actionMap.put("/cal_add", new AddCalAction());
//		actionMap.put("/cal_del", new DelCalAction());
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	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 action = actionMap.get(url);
//        action.execute(req, resp);
        ActionModel actionModel = configModel.get(url);
        actionModel.getType();
        try {
//        	如果没有配置给客户端一种提示
        	if(actionModel == null) {
        		throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
        	}
        	  //反射实例化
			Action action = (Action) Class.forName(actionModel.getType()).newInstance();
			String code = action.execute(req, resp);
			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 (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
        
	}
}

测试原来的加减法是否还能正常运行
在这里插入图片描述
在这里插入图片描述
4.3 将一组相关的操作放到一个Action中(反射调用方法)

DispatcherAction
     
      methodName:add/minus/mul/div

 CalAction extends DispatcherAction
        提供一组与execute方法的参数、返回值相同的方法,只有方法名不一样

代码演示:

增强版的子控制器ActionSupport:

package com.myy.framework;

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

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

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

	public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		从前台传递需要调用的方法名到后台,实现动态方法调用
		String methodName = req.getParameter("methodName");
//		思考:com.myy.web.CalAction  怎么获取 CalAction calAction = new CalAction();
		String code = null;
		try {
			Method m = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
//		打开访问权限
			m.setAccessible(true);
			code = (String) m.invoke(this, req,resp);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return code;
	}

}

简化mvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<!-- <action path="/cal_add" type="com.myy.web.AddCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
	<action path="/cal_del" type="com.myy.web.DelCalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action> -->
	
	<action path="/cal" type="com.myy.web.CalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
</config>

CalAction:

package com.myy.web;

import java.io.IOException;

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

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

public class CalAction extends ActionSupport{
	public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		Cal cal = new Cal(num1, num2);
		req.setAttribute("rs",Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
//	    req.getRequestDispatcher("/rs.jsp").forward(req, resp);	
		
		return "rs";
	}
	

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

改前台cal.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>
<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";
	}
	calForm.submit();
}


</script>
</head>
<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>

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

BeanUtils.populate(calBean, parameterMap);

      ModelDriver接口返回的对象不能为空
	  

代码演示:

模型驱动接口ModelDriven:

package com.myy.framework;

/**
 * 模型驱动接口
 *   作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
 * @author myy
 *
 * @param <T>
 */
public interface ModelDriven<T> {
   T getModel();
}

更改CalAction:

package com.myy.web;

import java.io.IOException;

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

import com.myy.entity.Cal;
import com.myy.framework.ActionSupport;
import com.myy.framework.ModelDriven;

public class CalAction extends ActionSupport implements ModelDriven<Cal>{
	private Cal cal = new Cal();
	public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		String num1 = req.getParameter("num1");
//		String num2 = req.getParameter("num2");
//		Cal cal = new Cal(num1, num2);
		req.setAttribute("rs",Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
//	    req.getRequestDispatcher("/rs.jsp").forward(req, resp);	
		
		return "rs";
	}
	

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


	public Cal getModel() {
		
		return cal;
	}
}

修改DispatecherServlet代码:

package com.myy.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 com.myy.web.AddCalAction;
import com.myy.web.DelCalAction;

/**
 * 中央控制器
 * 作用:
 *  接收用户请求,通过用户请求的url寻找指定的自控制器去处理业务
 *  
 *  1.对存放自控制器action容器的增强
 *  why:原来为了完成业务需求,需求不断修改框架的代码,这样设计是不合理的
 *  处理方式:参照web.xml的设计方法,来完成中央控制器管理控制器的动态配置
 * 
 * 2.处理结果码的跳转形式
 *   达到简化代码的目的
 *   
 * 3.将一组操作放到一个子控制器去完成
 * 
 * 4.处理jsp传递到后台的参数封装
 * 
 * @author myy
 *
 */
public class DispatecherServlet extends HttpServlet {

	private static final long serialVersionUID = 7187494273786588096L;

//	private Map<String,Action> actionMap = new HashMap<String,Action>();
	private ConfigModel configModel = null;
	
	
	public void init() {
//		http://localhost:8080/T237_mvc/cal_add.action
//		/T237_mvc/cal_add.action
//		actionMap.put("/cal_add", new AddCalAction());
//		actionMap.put("/cal_del", new DelCalAction());
		try {
			configModel = ConfigModelFactory.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	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 action = actionMap.get(url);
//        action.execute(req, resp);
        ActionModel actionModel = configModel.get(url);
        actionModel.getType();
        try {
//        	如果没有配置给客户端一种提示
        	if(actionModel == null) {
        		throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
        	}
        	  //反射实例化
			Action action = (Action) Class.forName(actionModel.getType()).newInstance();
			if(action instanceof ModelDriven) {
				ModelDriven  modelDriven = (ModelDriven) action;
				Object model = modelDriven.getModel();
//				给model赋值了,那么意味着在调用add/del方法的时候cal不再是空的了
				BeanUtils.populate(model, req.getParameterMap());
			}
			
			
			String code = action.execute(req, resp);
			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 (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
        
	}
}

测试代码是否成功运行

随便把乘除法也写了,代码如下
cal.jsp加上判断:
在这里插入图片描述

<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=cheng";
	}else if(v==4){
		calForm.action = "${pageContext.request.contextPath }/cal.action?methodName=chu";
	}
	calForm.submit();
}


</script>

CalAction:

package com.myy.web;

import java.io.IOException;

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

import com.myy.entity.Cal;
import com.myy.framework.ActionSupport;
import com.myy.framework.ModelDriven;

public class CalAction extends ActionSupport implements ModelDriven<Cal>{
	private Cal cal = new Cal();
	public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		String num1 = req.getParameter("num1");
//		String num2 = req.getParameter("num2");
//		Cal cal = new Cal(num1, num2);
		req.setAttribute("rs",Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
//	    req.getRequestDispatcher("/rs.jsp").forward(req, resp);	
		
		return "rs";
	}
	

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

	public String cheng(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("rs",Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("rs",Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	public Cal getModel() {
		
		return cal;
	}
}

测试乘数法运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4.5 使得框架的配置文件可变

注意:Action多例模式?因为Action的属性要用来接收参数

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

场景一:你改了默认的配置文件:
创建一个Source Folder文件中创建一个xml测试,如下图:
在这里插入图片描述
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>my_mvc</display-name>
 <servlet>
   <servlet-name>dispatecherServlet</servlet-name>
   <servlet-class>com.myy.framework.DispatecherServlet</servlet-class>
   <init-param>
      <param-name>mvcXmlLocation</param-name>
      <param-value>/myy.xml</param-value>
   </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>dispatecherServlet</servlet-name>
  <url-pattern>*.action</url-pattern>
 </servlet-mapping>
</web-app>

DispatecherServlet:

package com.myy.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 com.myy.web.AddCalAction;
import com.myy.web.DelCalAction;

/**
 * 中央控制器
 * 作用:
 *  接收用户请求,通过用户请求的url寻找指定的自控制器去处理业务
 *  
 *  1.对存放自控制器action容器的增强
 *  why:原来为了完成业务需求,需求不断修改框架的代码,这样设计是不合理的
 *  处理方式:参照web.xml的设计方法,来完成中央控制器管理控制器的动态配置
 * 
 * 2.处理结果码的跳转形式
 *   达到简化代码的目的
 *   
 * 3.将一组操作放到一个子控制器去完成
 * 
 * 4.处理jsp传递到后台的参数封装
 * 
 * 5.解决框架配置文件重名冲突问题
 * 
 * @author myy
 *
 */
public class DispatecherServlet extends HttpServlet {

	private static final long serialVersionUID = 7187494273786588096L;

//	private Map<String,Action> actionMap = new HashMap<String,Action>();
	private ConfigModel configModel = null;
	
	
	public void init() {
//		http://localhost:8080/T237_mvc/cal_add.action
//		/T237_mvc/cal_add.action
//		actionMap.put("/cal_add", new AddCalAction());
//		actionMap.put("/cal_del", new DelCalAction());
		try {
//			mvc地址默认为空
			String mvcXmlLocation = this.getInitParameter("mvcXmlLocation");
			if(null == mvcXmlLocation || "".equals(mvcXmlLocation)) {
				mvcXmlLocation = "mvc.xml";
			}
			System.out.println("mvcXmlLocation:"+mvcXmlLocation);
			configModel = ConfigModelFactory.newInstance(mvcXmlLocation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	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 action = actionMap.get(url);
//        action.execute(req, resp);
        ActionModel actionModel = configModel.get(url);
        actionModel.getType();
        try {
//        	如果没有配置给客户端一种提示
        	if(actionModel == null) {
        		throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
        	}
        	  //反射实例化
			Action action = (Action) Class.forName(actionModel.getType()).newInstance();
			if(action instanceof ModelDriven) {
				ModelDriven  modelDriven = (ModelDriven) action;
				Object model = modelDriven.getModel();
//				给model赋值了,那么意味着在调用add/del方法的时候cal不再是空的了
				BeanUtils.populate(model, req.getParameterMap());
			}
			
			
			String code = action.execute(req, resp);
			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 (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
        
	}
}

浏览器运行后打印的结果:
在这里插入图片描述

为了避免冲突

场景二:不冲突的时候
不需要配如下:
在这里插入图片描述
重新运行测试:
在这里插入图片描述

为默认的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值