MVC框架与增强
一.什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。
二.编程模式
- Model(模型)表示应用程序核心(比如数据库记录列表)
- 是应用程序中用于处理应用程序数据逻辑的部分,通常模型对象负责在数据库中cun存取数据。
- View(视图)显示数据(数据库记录)
- 是应用程序中处理数据显示的部分,通常视图是依据模型数据创建的。
- Controller(控制器)处理输入(写入数据库记录)
- 是应用程序中处理用户交互的部分,通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
三.MVC结构
- V
- jsp
- ios
- android
- C
- servlet
- action
- M
- 实体域模型(名词)
- 过程域模型(动词)
注1:不能跨层调用
注2:只能出现由上而下的调用
四.自定义MVC工作原理图
五.自定义MVC原理实现(加减乘除)
子控制器接口Action
- 用来直接处理浏览器发送过来的请求
package com.mvc.framework; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 子控制器
* 作用:用来直接处理浏览器发送过来的请求
* @author Administrator
*
*/
public interface Action {
String exxecute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
实体类Cal
package com.mvc.entity; public class Cal { private int num1;
private int num2;
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public Cal(int num1, int num2) {
super();
this.num1 = num1;
this.num2 = num2;
}
public Cal() {
super();
} }
子控制器AddCalAction(加)
package com.mvc.web; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mvc.entity.Cal;
import com.mvc.framework.Action; public class AddCalAction implements Action{ @Override
public String exxecute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()+cal.getNum2());
req.getRequestDispatcher("res.jsp").forward(req, resp);
return null;
}
}
在这里减乘除只要更改
子控制器req.setAttribute("req", cal.getNum1()+cal.getNum2());
中的+为- * /则可实现减乘除,提供减法类DelCalAction 乘法类MulCalAction 除法类DivCalAction 中央控制器DispatchrServlet
- 接收请求,通过请求寻找对应的子控制器
package com.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 com.mvc.web.AddCalAction;
import com.mvc.web.DelCalAction;
import com.mvc.web.DivCalAction;
import com.mvc.web.MulCalAction; /**
* 中央控制器
* 作用:接收请求,通过请求寻找对应的子控制器
* @author Administrator
*
*/
public class DispatchrServlet extends HttpServlet{ private Map<String, Action> ActionMap=new HashMap<>(); public void init() {
//加
ActionMap.put("/addCal", new AddCalAction());
//减
ActionMap.put("/delCal", new DelCalAction());
//乘
ActionMap.put("/mulCal", new MulCalAction());
//除
ActionMap.put("/divCal", new DivCalAction()); } @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 {
// TODO Auto-generated method stub
init();
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
Action action = actionMap.get(url);
action.execute(req, resp);
} }
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>JavaMVC</display-name>
<servlet>
<servlet-name>DispatchrServlet</servlet-name>
<servlet-class>com.mvc.framework.DispatchrServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DispatchrServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
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(num){
if (num==1) {
calForm.action="${pageContext.request.contextPath }/addCal.action"
}else if (num==2) {
calForm.action="${pageContext.request.contextPath }/delCal.action" }else if (num==3) {
calForm.action="${pageContext.request.contextPath }/mulCal.action"
}else if (num==4) {
calForm.action="${pageContext.request.contextPath }/divCal.action" }
calForm.submit();
} </script>
</head>
<body>
<form name="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>
运行结果
六.通过XML对自定义MVC框架进行增强
- 将子控制器信息动态配置到mvc.xml中
- 针对MVC框架的结果码进行处理
- 将一组操作放到一个子控制器中
- 利用模型驱动接口对mvc框架进行增强
- 解决框架配置文件的冲突问题
将建模导入到com.mvc.framework中
导入jar包
将子控制器信息动态配置到mvc.xml中
6.1 中央控制器DispatchrServlet
- 将所有子控制器都汇聚到ConfigModel
- 配置
- 反射实例化
package com.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 com.mvc.web.AddCalAction;
import com.mvc.web.DelCalAction;
import com.mvc.web.DivCalAction;
import com.mvc.web.MulCalAction; /**
* 中央控制器
* 作用:接收请求,通过请求寻找对应的子控制器
* @author Administrator
*
*/
public class DispatchrServlet extends HttpServlet{ //private Map<String, Action> ActionMap=new HashMap<>();
//第一次改进
//将所有子控制器都汇聚到ConfigModel
//在ConfigModel对象中包含了所有子控制器
private ConfigModel configModel; public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ActionMap.put("/addCal", new AddCalAction());
// ActionMap.put("/delCal", new DelCalAction());
// ActionMap.put("/mulCal", new MulCalAction());
// ActionMap.put("/divCal", new DivCalAction());
}
/**
*
*/
private static final long serialVersionUID = -7359199881120612454L; @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
init();
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
//配置
ActionModel actionModel = configModel.get(url);
if (actionModel==null) {
throw new RuntimeException("你没有配置action标签,找不到对应的子控制器来处理浏览器发送的请求"); }
//反射实例化
try {
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
action.exxecute(req, resp);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Action action=ActionMap.get(url); } }
配置mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<action path="/addCal" type="com.mvc.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> <action path="/delCal" type="com.mvc.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> <action path="/mulCal" type="com.mvc.web.MulCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> <action path="/divCal" type="com.mvc.web.DivCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> </config>
工厂模式ConfigModelFactory
package com.mvc.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();
}
}
}
6.2针对MVC框架的结果码进行处理
中央控制器DispatchrServlet
- 判断是重定向还是转发
- 做转发的处理
package com.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 com.mvc.web.AddCalAction;
import com.mvc.web.DelCalAction;
import com.mvc.web.DivCalAction;
import com.mvc.web.MulCalAction; /**
* 中央控制器
* 作用:接收请求,通过请求寻找对应的子控制器
* @author Administrator
*
*/
public class DispatchrServlet extends HttpServlet{ //private Map<String, Action> ActionMap=new HashMap<>();
//第一次改进
//将所有子控制器都汇聚到ConfigModel
//在ConfigModel对象中包含了所有子控制器
private ConfigModel configModel; public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ActionMap.put("/addCal", new AddCalAction());
// ActionMap.put("/delCal", new DelCalAction());
// ActionMap.put("/mulCal", new MulCalAction());
// ActionMap.put("/divCal", new DivCalAction());
}
/**
*
*/
private static final long serialVersionUID = -7359199881120612454L; @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
init();
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
//配置
ActionModel actionModel = configModel.get(url);
if (actionModel==null) {
throw new RuntimeException("你没有配置action标签,找不到对应的子控制器来处理浏览器发送的请求"); }
//反射实例化
try {
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
String code=action.exxecute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if (forwardModel!=null) {
String jspPath=forwardModel.getPath();
//判断是重定向还是转发
if ("false".equals(forwardModel.getRedirect())) {
//做转发的处理
req.getRequestDispatcher(jspPath).forward(req, resp);
}else {
resp.sendRedirect(req.getContextPath()+jspPath);
}
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Action action=ActionMap.get(url); } }
AddCalAction
package com.mvc.web; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mvc.entity.Cal;
import com.mvc.framework.Action; public class AddCalAction implements Action{ @Override
public String exxecute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()+cal.getNum2());
//req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
}
}
DelCalAction
package com.mvc.web; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mvc.entity.Cal;
import com.mvc.framework.Action; public class DelCalAction implements Action{ @Override
public String exxecute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()-cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} }
mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<action path="/addCal" type="com.mvc.web.AddCalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action> <action path="/delCal" type="com.mvc.web.DelCalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action> <action path="/mulCal" type="com.mvc.web.MulCalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action> <action path="/divCal" type="com.mvc.web.DivCalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action> </config>
ForwardModel
package com.mvc.framework;
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;
} }
6.3将一组操作放到一个子控制器中
- 对子控制器进行增强
ActionSupport增强版子控制器
package com.mvc.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;
/**
* 增强版子控制器
* 原来的子控制器只能一用户请求
* 有时候,用户请求是多个,但是都是操作同一张表,那么原有的子控制器代码编写繁琐
* 增强版的作用就是:将一组相关的操作放到一个Action中
* @author Administrator
*
*/
public class ActionSupport implements Action { @Override
public final String exxecute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String methodName=req.getParameter("methodName");
String code = null;
//class CalAction exends ActionSupport
// this在这里指的是CalAction他的一个类实例
try {
Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
code = (String) m.invoke(this, req,resp);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return code;
} }
将加减乘除方法放入CalAction 类中并继承子控制器ActionSupport
package com.mvc.web; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mvc.entity.Cal;
import com.mvc.framework.ActionSupport; public class CalAction extends ActionSupport{ public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()+cal.getNum2());
//req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()-cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String mul(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()*cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String div(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
// System.out.println(num1);
// System.out.println(num2);
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()/cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} }
mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<!-- <action path="/addCal" type="com.mvc.web.AddCalAction">-->
<!--<forward name="res" path="/res.jsp" redirect="false" />-->
<!--</action>--> <!--<action path="/delCal" type="com.mvc.web.DelCalAction">-->
<!-- <forward name="res" path="/res.jsp" redirect="false" />-->
<!--</action>--> <!--<action path="/mulCal" type="com.mvc.web.MulCalAction">-->
<!-- <forward name="res" path="/res.jsp" redirect="false" />-->
<!--</action>--> <!--<action path="/divCal" type="com.mvc.web.DivCalAction">-->
<!-- <forward name="res" path="/res.jsp" redirect="false" />-->
<!--</action>--> <action path="/cal" type="com.mvc.web.CalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action>
</config>
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(num){
if (num==1) {
calForm.action="${pageContext.request.contextPath }/cal.action?methodName=add"
}else if (num==2) {
calForm.action="${pageContext.request.contextPath }/cal.action?methodName=del" }else if (num==3) {
calForm.action="${pageContext.request.contextPath }/cal.action?methodName=mul"
}else if (num==4) {
calForm.action="${pageContext.request.contextPath }/cal.action?methodName=div" }
calForm.submit();
} </script>
</head>
<body>
<form name="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>
6.4解决框架配置文件的冲突问题
DispatchrServlet 中央控制器加强读取xml
public void init() {
try {
String xmlPath= this.getInitParameter("xmlPath");
if (xmlPath == null || "".equals(xmlPath)) {
configModel=ConfigModelFactory.newInstance();
}else {
configModel=ConfigModelFactory.newInstance(xmlPath);
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在src下建一个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>JavaMVC</display-name>
<servlet>
<servlet-name>DispatchrServlet</servlet-name>
<servlet-class>com.mvc.framework.DispatchrServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatchrServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
6.5利用模型驱动接口对mvc框架进行增强
- 利用ModelDrive接口对java对象赋值(反射读写属性)
ModelDrivern<T>模型驱动接口
package com.mvc.web;
/**
* 模型驱动接口
* 作用将jsp所有传递过来的参数以及参数值
* 自动封装到浏览器索要操作的实体类
* @author Administrator
*
*/
public interface ModelDrivern<T> { T getModel();
}
CalAction
package com.mvc.web; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mvc.entity.Cal;
import com.mvc.framework.ActionSupport; public class CalAction extends ActionSupport implements ModelDrivern<Cal>{ private Cal cal=new Cal(); public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
//// System.out.println(num1);
//// System.out.println(num2);
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()+cal.getNum2());
//req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // TODO Auto-generated method stub
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
//// System.out.println(num1);
//// System.out.println(num2);
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()-cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String mul(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
//// System.out.println(num1);
//// System.out.println(num2);
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()*cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} public String div(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
//// System.out.println(num1);
//// System.out.println(num2);
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("req", cal.getNum1()/cal.getNum2());
// req.getRequestDispatcher("res.jsp").forward(req, resp);
return "res";
} @Override
public Cal getModel() {
// TODO Auto-generated method stub
return cal;
} }
DispatchrServlet
package com.mvc.framework; import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; 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.jasper.tagplugins.jstl.core.ForEach; import com.mvc.web.AddCalAction;
import com.mvc.web.DelCalAction;
import com.mvc.web.DivCalAction;
import com.mvc.web.ModelDrivern;
import com.mvc.web.MulCalAction; /**
* 中央控制器
* 作用:接收请求,通过请求寻找对应的子控制器
* @author Administrator
*
*/
public class DispatchrServlet extends HttpServlet{ //private Map<String, Action> ActionMap=new HashMap<>();
//第一次改进
//将所有子控制器都汇聚到ConfigModel
//在ConfigModel对象中包含了所有子控制器
private ConfigModel configModel; public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ActionMap.put("/addCal", new AddCalAction());
// ActionMap.put("/delCal", new DelCalAction());
// ActionMap.put("/mulCal", new MulCalAction());
// ActionMap.put("/divCal", new DivCalAction());
}
/**
*
*/
private static final long serialVersionUID = -7359199881120612454L; @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
init();
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
//配置
ActionModel actionModel = configModel.get(url);
if (actionModel==null) {
throw new RuntimeException("你没有配置action标签,找不到对应的子控制器来处理浏览器发送的请求"); }
//反射实例化
try {
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
//调用赋值
//action就是package com.mvc.framework.CalAction;
if (action instanceof ModelDrivern) {
ModelDrivern mdDrivern=(ModelDrivern) action;
//此时的model的所有属性是null的
Object model = mdDrivern.getModel();
BeanUtils.populate(model, req.getParameterMap());
//原理
//我们可以将req.getParameterMap();的值通过反射的方式将其塞进model实例
// Map<String, String[]> parameterMap = req.getParameterMap();
// Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
// Class<? extends Object> clz = model.getClass();
// for (Entry<String, String[]> entry : entrySet) {
// Field field = clz.getField(entry.getKey());
// field.set(model, entry.getValue());
// }
} String code=action.exxecute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if (forwardModel!=null) {
String jspPath=forwardModel.getPath();
//判断是重定向还是转发
if ("false".equals(forwardModel.getRedirect())) {
//做转发的处理
req.getRequestDispatcher(jspPath).forward(req, resp);
}else {
resp.sendRedirect(req.getContextPath()+jspPath);
}
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
MVC框架与增强的更多相关文章
- 前端MVC框架Backbone 1.1.0源码分析(一)
前言 如何定义库与框架 前端的辅助工具太多太多了,那么我们是如何定义库与框架? jQuery是目前用的最广的库了,但是整体来讲jQuery目的性很也明确针对“DOM操作”,当然自己写一个原生态方法也能 ...
- 从零开始学 Java - 搭建 Spring MVC 框架
没有什么比一个时代的没落更令人伤感的了 整个社会和人都在追求创新.进步.成长,没有人愿意停步不前,一个个老事物慢慢从我们生活中消失掉真的令人那么伤感么?或者说被取代?我想有些是的,但有些东西其实并不是 ...
- mvc设计模式和mvc框架的区别
Spring中的新名称也太多了吧!IOC/DI/MVC/AOP/DAO/ORM... 对于刚刚接触spring的我来说确实晕了头!可是一但你完全掌握了一个概念,那么它就会死心塌地的为你服务了.这可比女 ...
- [Java] 使用 Spring 2 Portlet MVC 框架构建 Portlet 应用
转自:http://www.ibm.com/developerworks/cn/java/j-lo-spring2-portal/ Spring 除了支持传统的基于 Servlet 的 Web 开发之 ...
- Backbone.Events—纯净MVC框架的双向绑定基石
Backbone.Events-纯净MVC框架的双向绑定基石 为什么Backbone是纯净MVC? 在这个大前端时代,各路MV*框架如雨后春笋搬涌现出来,在infoQ上有一篇 12种JavaScrip ...
- Spring MVC 简述:从MVC框架普遍关注的问题说起
任何一个完备的MVC框架都需要解决Web开发过程中的一些共性的问题,比如请求的收集与分发.数据前后台流转与转换,当前最流行的SpringMVC和Struts2也不例外.本文首先概述MVC模式的分层思想 ...
- Spring Web MVC框架简介
Web MVC framework框架 Spring Web MVC框架简介 Spring MVC的核心是`DispatcherServlet`,该类作用非常多,分发请求处理,配置处理器映射,处理视图 ...
- 自定义简单算法MVC框架
什么是MVC框架 MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写, 它是一种软件设计典范,用一种业务逻辑.数据 ...
- 4-2 Spring MVC框架-01
Spring MVC框架-01 Ⅰ.接收客户端请求 1. 关于Spring MVC框架 Spring MVC是基于Spring框架基础之上的 作用: 接收请求,响应结果,处理异常 主要解决了后端服务器 ...
随机推荐
- 「雅礼集训 2017 Day1」字符串 SAM、根号分治
LOJ 注意到\(qk \leq 10^5\),我们很不自然地考虑根号分治: 当\(k > \sqrt{10^5}\),此时\(q\)比较小,与\(qm\)相关的算法比较适合.对串\(s\)建S ...
- MATLAB datenum日期转换为Python日期
摘要 MATLAB datenum时间格式参数众多,本文只简单关注 units 参数,即基准年份和计时度量(天.小时). 命令行演示在 ipython 和 Octave 中进行. 示例1:小时制,基准 ...
- C# SQl通过对视图数据二次查询,统计数据
问题描述: 原数据---------需要在原视图数据中,统计出每个Device_Num设备号下面的交易的总额和分别统计出微信支付宝的交易总额. 解决:从上图数据没办法使用直接查询出要求的数据. .1. ...
- 使用VBA将Excel指定单元格数据、字符串或者图表对象插入到Word模板指定书签处
准备工作: 1.首先需要提供一个word模板,并且标记好您要插入书签的位置,定义书签的命名.如图 2.模拟您要插入的Excel原始数据和图表对象 插入代码如下: Private Sub Command ...
- linuxmint安装Tools找不到Tools的压缩包问题
安装Linuxmint之后按照惯例安装Tools,打开桌面上的Tools光盘之后找不到压缩包. PS:因为已经装好了,就不上图了,按照下面的步骤做就没有问题了. 1:找到vmware的安装目录下的li ...
- Java自学-操作符 逻辑操作符
Java的逻辑运算符 逻辑运算符 示例 1 : 长路与 和 短路与 无论长路与还是短路与 两边的运算单元都是布尔值 都为真时,才为真 任意为假,就为假 区别: 长路与 两侧,都会被运算 短路与 只要第 ...
- JS JQUERY实现滚动条自动滚到底的方法
$(function(){ var h = $(document).height()-$(window).height(); $(document).scrollTop(h); }); \ windo ...
- Android Handler类 发送消息-post()和postDelay(), Looper讲解
https://blog.csdn.net/weixin_41101173/article/details/79701832 首先,post和postDelay都是Handler的方法,用以在子线程中 ...
- IVS_原理
智能视频分析技术指计算机图像视觉分析技术,是人工智能研究的一个分支,它在图像及图像描述之间建立映射关系,从而使计算机能够通过数字图像处理和分析来理解视频画面中的内容.智能视频分析技术涉及到模式识别.机 ...
- spec开发思路以及理解
一.spec说明 描述:编写SEPC采用创联公司自主开发的CIT语言,它是一种过程化的.类似数据库编码的语言.SPEC中除了关键字外提倡使用中文. 理解:可以理解为业务逻辑层.链接前台页面和后台数据库 ...