自定义MVC框架
1. 什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
2. MVC结构
v :(视图)
jsp/ios/android
c:(控制器)
servlet/action
M:(模型)
实体域模型(名词)
过程域模型(动词)
注1:不能跨层调用
注2:只能出现由上而下的调用
3.自定义MVC工作原理图:
主控制动态调用子控制器调用完成具体的业务逻辑
(火车、控制台、车轨)
请求、主控制器、子控制器
4.通过XML对自定义mvc框架进行增强:
mvc需要的jar包:
** ActionModel 用来描述action标签**
package com.framewrok;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 用来描述action标签
* @author Administrator
*
*/
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);
}
}
ConfigModel 用来描述config标签
package com.framewrok;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 用来描述config标签
* @author Administrator
*
*/
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);
}
}
ConfigModelFactory 工厂模式创建config建模对象
package com.framewrok;
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("forwardModel");
System.out.println(actionModel.getType());
System.out.println(forwardModel.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ForwardModel 用来描述forward标签
package com.framewrok;
import java.io.Serializable;
/**
* 用来描述forward标签
* @author Administrator
*
*/
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;
}
}
** mvc.xml 配置文件 可以根据需求修改内容**
<config>
<action path="/addCal" type="com.web.AddCalAction">
<forward name="res" path="/showshu.jsp" redirect="false" />
</action>
<action path="/delCal" type="com.web.DelCalAction">
<forward name="res" path="/showshu.jsp" redirect="false" />
</action>
<action path="/cheCal" type="com.web.CheCalAction">
<forward name="res" path="/showshu.jsp" redirect="false" />
</action>
<action path="/chuCal" type="com.web.ChuCalAction">
<forward name="res" path="/showshu.jsp" redirect="false" />
</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(val) {
if(val==1){
calFoem.action="${pageContext.request.contextPath}/addCal.action";
}else if(val==2){
calFoem.action="${pageContext.request.contextPath}/delCal.action";
}else if(val==3){
calFoem.action="${pageContext.request.contextPath}/cheCal.action";
}else if(val==4){
calFoem.action="${pageContext.request.contextPath}/chuCal.action";
}
calFoem.submit();
}
</script>
<body>
<form id="calFoem" action="" method="post">
数值1:<input type="text" name="num1">
数值2:<input type="text" name="num2">
<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 songwanxi_mvc.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 web.AddCalAction;
import web.CCalAction;
import web.DelCalAction;
import web.XCalAction;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
*
* 五步增强:
* 1、对存放子控制器action容器的增强(类似web.xml实例化 反射)
* 为什么:原来为了完成业务需求,需要不断修改框架代码,这样的设计不合理
* 处理方式:参照web.xml的设计方法,来完成中央控制器来管理子控制器的动态配置
*
* @author 10570
*
*/
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("/che", new XCalAction());
// actionMap.put("/chu", 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.framewrok;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
//void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
① 加法控制器:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.framewrok.Action;
public class AddCalAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//加
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(num1)+Integer.valueOf(num2));
//转发
//req.getRequestDispatcher("/showshu.jsp").forward(req, resp);
// resp.sendRedirect("/showshu.jsp");
return "res";
}
/* @Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//加
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(num1)+Integer.valueOf(num2));
//转发
req.getRequestDispatcher("/showshu.jsp").forward(req, resp);
}*/
}
② 减法控制器:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.framewrok.Action;
public class DelCalAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//减
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(num1)-Integer.valueOf(num2));
return "res";
}
//减:
// public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// //加
// //获取值
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
// //把值存进在req里面
// req.setAttribute("res", Integer.valueOf(num1)-Integer.valueOf(num2));
//
// //转发
// req.getRequestDispatcher("showshu.jsp").forward(req, resp);
// }
}
③ 乘法:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.framewrok.Action;
public class CheCalAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(num1) * Integer.valueOf(num2));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
/*@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(num1) * Integer.valueOf(num2));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
}
*/
}
④ 除法:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.framewrok.Action;
public class ChuCalAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(num1)/Integer.valueOf(num2));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
/*@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(num1)/Integer.valueOf(num2));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
}*/
}
在这里插入图片描述
处理JSP专递到后台的参数
修改子控制器页面:
例如:AddCalAction
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.framewrok.Action;
public class AddCalAction implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//加
//获取值
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(num1)+Integer.valueOf(num2));
//转发
//req.getRequestDispatcher("/showshu.jsp").forward(req, resp);
// resp.sendRedirect("/showshu.jsp");
return "res";
}
}
中央控制器:
package com.framewrok;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过请求的URL寻求找到指定的值控制器去处理
*
* 1.对存放的子控制器的action容器的增强
* ?:原来为了完成物业需求不断修改框架的代码,这样设计师不合理的;
* 处理方法:参照web.xml的实际方法,来完成中央控制管理子控制的动态配置
*
*
* 2.处理结果的调转形式
* 达到简化代码目的
*
*
* 3.将一组操作放到一个子控制器去完成
*
* 4.处理JSP专递到后台的参数
*
* 5.解决框架配置文件重命名冲突问题
* @author 125x
*
*/
public class DispathcherServlet extends HttpServlet{
private static final long serialVersionUID = 720508079514331069L;
private ConfigModel configModel=null;
//对应关系
//private Map<String,Action> actionMap=new HashMap<String, Action>();
//初始化的方法
public void init() {
//增强前
//http://localhost:8080/Mvc/addCal.action
/*actionMap.put("/addCal",new AddCalAction());
actionMap.put("/delCal", new DelCalAction());
actionMap.put("/cheCal",new CheCalAction());
actionMap.put("/chuCal",new ChuCalAction());*/
try {
//增强后
String mvcXmlLocation=this.getInitParameter("mvcXmlLocation");
configModel=ConfigModelFactory.newInstance(mvcXmlLocation);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
init();
String url=req.getRequestURI();//获取xxx.action
System.out.println("1url:"+url);
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
System.out.println("2url:"+url);
//Action action=new AddCalAction();
//列如
//实现了父类所有的方法
//class Student extend Person;
//Person p=new Student();
//拿到对应的子控制器
/*Action action = actionMap.get(url);
action.execute(req, resp);*/
ActionModel actionModel= configModel.get(url);
System.out.println("actionModel:"+actionModel);
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
Action action= (Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriver) {
ModelDriver modelDriver=(ModelDriver) action;
Object model= modelDriver.getModel();
//给model赋值了,那么就意味着在调用add/del方法的时候cal不再是空的了
BeanUtils.populate(model, req.getParameterMap());
}
System.out.println("action"+action);
System.out.println(actionModel.getType());
String code=action.execute(req, resp);
System.out.println("code"+code);
ForwardModel forwardModel= actionModel.get(code);
System.out.println("forwardModel"+forwardModel);
if("false".equals(forwardModel.getRedirect())){
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else{
//注意默认缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4.3将一组相关的操作放到一个Action中(反射调用方法)
①新建ActionSupport
package com.framewrok;
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 125x
*
*/
public class ActionSuppot implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从前台专需要的的方法名到后台,实现动态方法调用
String methodName=req.getParameter("methodName");
//思考:com.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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
}
② 新建ClaAction 集中所有子控制器
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Cal;
import com.framewrok.ActionSuppot;
import com.framewrok.ModelDriver;
public class CalAction extends ActionSuppot {
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");*/
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
//转发
//req.getRequestDispatcher("/showshu.jsp").forward(req, resp);
// resp.sendRedirect("/showshu.jsp");
return "res";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//减
//获取值
/*String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存进在req里面
//req.setAttribute("res", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
return "res";
}
public String che(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值器
/*String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1()) * Integer.valueOf(cal.getNum2()));
//转发
//req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
/* String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
}
③修改mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/Cal" type="com.web.CalAction">
<forward name="res" path="/showshu.jsp" redirect="false" />
</action>
</config>
④ show.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(val) {
if(val==1){
calFoem.action="${pageContext.request.contextPath}/Cal.action?methodName=add";
}else if(val==2){
calFoem.action="${pageContext.request.contextPath}/Cal.action?methodName=del";
}else if(val==3){
calFoem.action="${pageContext.request.contextPath}/Cal.action?methodName=che";
}else if(val==4){
calFoem.action="${pageContext.request.contextPath}/Cal.action?methodName=chu";
}
calFoem.submit();
}
</script>
<body>
<form id="calFoem" action="" method="post">
数值1:<input type="text" name="num1">
数值2:<input type="text" name="num2">
<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利用ModelDriven接口对Java对象进行赋值(反射读写方法)
①写一个ModelDriven
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Cal;
import com.framewrok.ActionSuppot;
import com.framewrok.ModelDriver;
public class CalAction extends ActionSuppot implements ModelDriver<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");*/
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
//转发
//req.getRequestDispatcher("/showshu.jsp").forward(req, resp);
// resp.sendRedirect("/showshu.jsp");
return "res";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//减
//获取值
/*String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存进在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
return "res";
}
public String che(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值器
/*String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1()) * Integer.valueOf(cal.getNum2()));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取值
/* String num1=req.getParameter("num1");
String num2=req.getParameter("num2");*/
//把值存放在req里面
req.setAttribute("res", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
//转发
req.getRequestDispatcher("showshu.jsp").forward(req, resp);
return "res";
}
@Override
public Cal getModel() {
return cal;
}
}
③ 中央控制器中j加入:
package com.framewrok;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过请求的URL寻求找到指定的值控制器去处理
*
* 1.对存放的子控制器的action容器的增强
* ?:原来为了完成物业需求不断修改框架的代码,这样设计师不合理的;
* 处理方法:参照web.xml的实际方法,来完成中央控制管理子控制的动态配置
*
*
* 2.处理结果的调转形式
* 达到简化代码目的
*
*
* 3.将一组操作放到一个子控制器去完成
*
* 4.处理JSP专递到后台的参数
*
* 5.解决框架配置文件重命名冲突问题
* @author 125x
*
*/
public class DispathcherServlet extends HttpServlet{
private static final long serialVersionUID = 720508079514331069L;
private ConfigModel configModel=null;
//对应关系
//private Map<String,Action> actionMap=new HashMap<String, Action>();
//初始化的方法
public void init() {
//增强前
//http://localhost:8080/Mvc/addCal.action
/*actionMap.put("/addCal",new AddCalAction());
actionMap.put("/delCal", new DelCalAction());
actionMap.put("/cheCal",new CheCalAction());
actionMap.put("/chuCal",new ChuCalAction());*/
try {
//增强后
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
init();
String url=req.getRequestURI();//获取xxx.action
System.out.println("1url:"+url);
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
System.out.println("2url:"+url);
//Action action=new AddCalAction();
//列如
//实现了父类所有的方法
//class Student extend Person;
//Person p=new Student();
//拿到对应的子控制器
/*Action action = actionMap.get(url);
action.execute(req, resp);*/
ActionModel actionModel= configModel.get(url);
System.out.println("actionModel:"+actionModel);
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
Action action= (Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriver) {
ModelDriver modelDriver=(ModelDriver) action;
Object model= modelDriver.getModel();
//给model赋值了,那么就意味着在调用add/del方法的时候cal不再是空的了
BeanUtils.populate(model, req.getParameterMap());
}
System.out.println("action"+action);
System.out.println(actionModel.getType());
String code=action.execute(req, resp);
System.out.println("code"+code);
ForwardModel forwardModel= actionModel.get(code);
System.out.println("forwardModel"+forwardModel);
if("false".equals(forwardModel.getRedirect())){
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else{
//注意默认缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException 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>Mvc</display-name>
<servlet>
<servlet-name>DispathcherServlet</servlet-name>
<servlet-class>com.framewrok.DispathcherServlet</servlet-class>
<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/cbw</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispathcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
如下图: