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框架基础之上的 作用: 接收请求,响应结果,处理异常 主要解决了后端服务器 ...
随机推荐
- 「UNR#2」黎明前的巧克力
「UNR#2」黎明前的巧克力 解题思路 考虑一个子集 \(S\) 的异或和如果为 \(0\) 那么贡献为 \(2^{|S|}\) ,不难列出生产函数的式子,这里的卷积是异或卷积. \[ [x^0]\p ...
- Oracle查询所有字段另加两个拼接字段的操作
Oracle查询所有字段,再加两个字段拼接, select a.*,(SNO||SNAME) from TEST_STUDENT a; 同理,查询所有字段,其中两个字段求和:(SNO和SAGE都是NU ...
- Replication:The replication agent has not logged a progress message in 10 minutes.
打开Replication Monitor,在Subscription Watch List Tab中,发现有大量的status= “Performance critical” 的黄色Warning, ...
- 开发dubbo应用程序(二)dubbo注册中心相关概述
1.注册中心概述 在Dubbo微服务体系中,注册中心是其核心组件之一.Dubbo通过注册中心实现了分布式环境中各微服务之间的注册与发现,是各分布式节点之间的纽带.其主要作用如下: 动态加入.一个服 ...
- B树索引最通俗易懂的介绍
先来一段有莫的对话: 前几天下班回到家后正在处理一个白天没解决的bug,厕所突然传来对象的声音: 对象:xx,你有<时间简史>吗? 我:我去!妹子,你这啥癖好啊,我有时间也不会去捡屎 ...
- .NET Core MD5加密 32位和16位
public class MD5Help { //此代码示例通过创建哈希字符串适用于任何 MD5 哈希函数 (在任何平台) 上创建 32 个字符的十六进制格式哈希字符串官网案例改编 /// <s ...
- 更新.net core 3.0,dotnet ef命令无法使用的解决办法
之前项目采用.net core 2.2 实现,今天更新vs2019,系统.net core也被升级到3.0,在cmd中使用dotnet ef命令出现 “无法执行,因为找不到指定的命令或文件.可能的原因 ...
- css, js 项目练习之网页换肤
首先,该练习参考自:https://www.jianshu.com/p/2961d9c317a3 我就直接上代码了(颜色可以自己调). HTML: <nav> <li>< ...
- 面试题:什么叫2B树
在B树的基础上,每个节点有两个域,且他们是有顺序的,在层次上的又满足二叉排序树的性质
- grub破解和bios加密
grub破解通过单用户模式,可以实现修改密码 grub加密以后,只能通过bios解除grub密码,方法如下 进入bios 修改启动方式,从CD启动 加载系统镜像,原系统默认挂载到/mnt/sysima ...