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框架基础之上的 作用: 接收请求,响应结果,处理异常 主要解决了后端服务器 ...
随机推荐
- Replication:The replication agent has not logged a progress message in 10 minutes.
打开Replication Monitor,在Subscription Watch List Tab中,发现有大量的status= “Performance critical” 的黄色Warning, ...
- Github 上优秀的 Java 项目推荐
1.JavaGuide 地址:Snailclimb/JavaGuide [Java学习+面试指南] 一份涵盖大部分Java程序员所需要掌握的核心知识. 2.DoraemonKit 地址:didi/Do ...
- B/S架构详解
学习笔记: * B/S架构详解 * 资源分类: 1. 静态资源: * 使用静态网页开发技术发布的资源. * 特点: ...
- java jsp文件报错解决方法
初次使用java开发 下载好代码之后,用maven编译都是ok的,第二天,打开项目一看,好的web项目的jsp文件提示错误,后面,查了下问题,是tomcat没有配置路径导致的问题,现在大致记录一下解决 ...
- N(C)O(S)I(P)P 2019 退役记
N(C)O(S)I(P)P 2019 退役记 day-4 今天下午老师突然咕了,于是一下午欢乐时光 今天上午考试T3线段树维护个区间加,区间乘 一遍过编译,一遍过样例(第一次,俺比较弱(虽然也发现和暴 ...
- drf之视图类与路由
视图 Django REST framwork 提供的视图的主要作用: 控制序列化器的执行(检验.保存.转换数据) 控制数据库查询的执行 2个视图基类 APIView rest_framework.v ...
- 剑指前端(前端入门笔记系列)——DOM(属性节点)
DOM(属性节点) 属性节点没有过参加家族关系中,其专用选择器:attributes,返回值为对象的形式,它的键是索引值,也就是用对象模拟了一个伪数组,DOM中选择器返回的都是伪数组(可以使用数组的形 ...
- APS应用案例|纽威阀门实现高效排产
企业背景: 苏州纽威阀门股份有限公司(下文简称:纽威阀门)成立于1997年,总部设在江苏苏州.自成立以来一直致力于工业阀门的研发与制造,以为客户提供全套工业阀门解决方案为目标.纽威阀门通过企业的努力发 ...
- RPC相关知识
为什么要进行系统拆分,为什么要用dubbo RPC的由来,基本架构,实现原理,整个调用过程经历了哪几步 Java动态代理及 RPC框架介绍 一篇文章了解RPC框架原理 dubbo详解及demo实例 d ...
- AOP的动态实现cglib和jdk
动态代理的两种实现以:cglib和jdk,spring的aop(切面)的实现原理就是采用的动态代理技术. 看完代码.动态代理的作用是什么: Proxy类的代码量被固定下来,不会因为业务的逐渐庞大而庞大 ...