1. 什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码, 核心思想:各司其职
2. MVC结构
V
jsp/ios/android
C
servlet/action
M
实体域模型(名词)
过程域模型(动词)
web 做浏览器请求分发
service 调用dao处理项目业务的
dao 操作数据库
自定义mvc原理图
上课案例:
用自定义mvc完成一个简洁界面版的加减乘除
自定义mvc工作原理的代码体现:
实体类:
package com.zhoutubing.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();
}
}
中央控制器
package com.zhoutubing.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 javax.swing.ActionMap;
import com.zhoutubing.web.AddCalAction;
import com.zhoutubing.web.CheCalAction;
import com.zhoutubing.web.ChuCalAction;
import com.zhoutubing.web.DelCalAction;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
private Map<String, Action> actionMap = new HashMap<>();
public void init() {
actionMap.put("/addCal", new AddCalAction());
actionMap.put("/delCal", new DelCalAction());
actionMap.put("/cheCal", new CheCalAction());
actionMap.put("/chuCal", new ChuCalAction());
}
@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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
Action action = actionMap.get(url);
action.execute(req, resp);
}
}
子控制器
package com.zhoutubing.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:用来直接处理浏览器发送过来的请求
* @author Administrator
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp);
}
加减乘除的四个方法
加
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class AddCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() + cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
减
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class DelCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() - cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
乘
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class CheCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() * cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
除
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class ChuCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() / cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
配置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>web05_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
写一个jsp页面(包含了4中方法):
<%@ 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 }/cheCal.action";
}else if(num==4){
calForm.action="${pageContext.request.contextPath }/chuCal.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>
结果页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
结果:${res }
</body>
</html>
运行cal.jsp文件,界面效果:
加法:
结果:
减法:
结果:
乘法:
结果:
除法:
结果:
上面写的都是普通版的
3、通过XML对自定义mvc框架进行增强
总共有5种方式
3.1 将Action的信息配置到xml(反射实例化)
解决了在框架代码中去改动,以便于完成客户需求,这个是不合理的
-----------------这下面的代码5种方式都是共用的,我这里就放一块了---------------------
实体类:
package com.zhoutubing.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();
}
}
工厂类:
ActionModel:
package com.zhoutubing.framework;
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:
package com.zhoutubing.framework;
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:
package com.zhoutubing.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();
}
}
}
ForwardModel:
package com.zhoutubing.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;
}
}
-----------------到这里为止---------------------
中央控制器:
package com.zhoutubing.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 javax.swing.ActionMap;
import com.zhoutubing.web.AddCalAction;
import com.zhoutubing.web.CheCalAction;
import com.zhoutubing.web.ChuCalAction;
import com.zhoutubing.web.DelCalAction;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
// 在configModel对象中包含了所有的子控制器信息
private ConfigModel configModel;
public void init() {
try {
configModel = ConfigModelFactory.newInstance();
} 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();
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.execute(req, resp);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
子控制器:
package com.zhoutubing.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:用来直接处理浏览器发送过来的请求
* @author Administrator
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp);
}
加减乘除的四个方法
加
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class AddCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() + cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
减
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class DelCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() - cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
乘
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class CheCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() * cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
除
package com.zhoutubing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class ChuCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() / cal.getNum2());
try {
req.getRequestDispatcher("res.jsp").forward(req, resp);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
配置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>web05_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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 }/cheCal.action";
}else if(num==4){
calForm.action="${pageContext.request.contextPath }/chuCal.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>
结果页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
方式1结果:${res }
</body>
</html>
测试结果:
我这就只展示除法的结果了,加减乘都是可以的
3.2 通过结果码控制页面的跳转
因为上面已经写了实体类和工厂模式的代码了,所以我这里就不写了
中央控制器:
package com.zhoutubing.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 javax.swing.ActionMap;
import com.zhoutubing.web.AddCalAction;
import com.zhoutubing.web.CheCalAction;
import com.zhoutubing.web.ChuCalAction;
import com.zhoutubing.web.DelCalAction;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
private ConfigModel configModel;
public void init() {
try {
configModel = ConfigModelFactory.newInstance();
} 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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(url);
try {
Action action = (Action)Class.forName(actionModel.getType()).newInstance();
String code = action.execute(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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
子控制器:
package com.zhoutubing.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:用来直接处理浏览器发送过来的请求
* @author Administrator
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp);
}
加减乘除4中方法:
加法:
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class AddCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() + cal.getNum2());
return "res";
}
}
减法:
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class DelCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() - cal.getNum2());
return "res";
}
}
乘法:
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class CheCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() * cal.getNum2());
return "res";
}
}
除法:
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.Action;
public class ChuCalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() / cal.getNum2());
return "res";
}
}
结果res.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 }/cheCal.action";
}else if(num==4){
calForm.action="${pageContext.request.contextPath }/chuCal.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>
结果界面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
方式2结果:${res }
</body>
</html>
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>web05_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
乘法运行结果:
3.3 将一组相关的操作放到一个Action中(反射调用方法)
提供一组与execute方法的参数、返回值相同的方法,只有方法名不一样
中央控制器:
package com.zhoutubing.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 javax.swing.ActionMap;
import com.zhoutubing.web.AddCalAction;
import com.zhoutubing.web.CheCalAction;
import com.zhoutubing.web.ChuCalAction;
import com.zhoutubing.web.DelCalAction;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
// 在configModel对象中包含了所有的子控制器信息
private ConfigModel configModel;
public void init() {
try {
configModel = ConfigModelFactory.newInstance();
} 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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(url);
try {
Action action = (Action)Class.forName(actionModel.getType()).newInstance();
String code = action.execute(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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
子控制器:
package com.zhoutubing.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:用来直接处理浏览器发送过来的请求
* @author Administrator
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp);
}
增强版的子控制器:
package com.zhoutubing.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 增强版的子控制器
* 原来的子控制器只能一个用户请求
* 有时候,用户请求是多个,但是都是操作用一张表,那么原来有的子控制器代码编写繁琐
* 增强版的作用就是
* 将一组相关的操作放到一个Action中
* @author Administrator
*
*/
public class ActionSupport implements Action {
@Override
public final String execute(HttpServletRequest req, HttpServletResponse resp) {
String methodName = req.getParameter("methodName");
String code = null;
// 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: handle exception
e.printStackTrace();
}
return code;
}
}
加减乘除方法与上面的两种方式不同,这里是写到一个类里面了,简化了操作
CalAction:
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.ActionSupport;
public class CalAction extends ActionSupport {
public String add(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() + cal.getNum2());
return "res";
}
public String del(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() - cal.getNum2());
return "res";
}
public String che(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() * cal.getNum2());
return "res";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");
Cal cal = new Cal(Integer.valueOf(num1), Integer.valueOf(num2));
req.setAttribute("res", cal.getNum1() / cal.getNum2());
return "res";
}
}
mvc.xml文件配置(简化了很多,就算你有很多个方法,这里只用配置一个就行了)
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.zhoutubing.web.CalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action>
</config>
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>web05_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
res.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=che";
}else if(num==4){
calForm.action="${pageContext.request.contextPath }/cal.action?methodName=chu";
}
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>
结果页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
方式3结果:${res }
</body>
</html>
3.4 利用ModelDriver接口对Java对象进行赋值(反射读写属性)
BeanUtils.populate(calBean, parameterMap);
ModelDriver接口返回的对象不能为空
模型驱动接口
package com.zhoutubing.framework;
/**
* 模型驱动接口
* 作用是将jsp所有传递过来的参数都
* 自动封装到浏览器所要操作的实体类中
* @author Administrator
*
*/
public interface ModelDrivern<T> {
T getModel();
}
CalAction:(简化了很多代码)
package com.zhoutubing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhoutubing.entity.Cal;
import com.zhoutubing.framework.ActionSupport;
import com.zhoutubing.framework.ModelDrivern;
public class CalAction extends ActionSupport implements ModelDrivern<Cal>{
private Cal cal = new Cal();
public String add(HttpServletRequest req, HttpServletResponse resp) {
req.setAttribute("res", cal.getNum1() + cal.getNum2());
return "res";
}
public String del(HttpServletRequest req, HttpServletResponse resp) {
req.setAttribute("res", cal.getNum1() - cal.getNum2());
return "res";
}
public String che(HttpServletRequest req, HttpServletResponse resp) {
return "res";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) {
return "res";
}
@Override
public Cal getModel() {
// TODO Auto-generated method stub
return cal;
}
}
中央控制器:
package com.zhoutubing.framework;
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 javax.swing.ActionMap;
import org.apache.commons.beanutils.BeanUtils;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
// 在configModel对象中包含了所有的子控制器信息
private ConfigModel configModel;
public void init() {
try {
configModel = ConfigModelFactory.newInstance();
} 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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(url);
try {
Action action = (Action)Class.forName(actionModel.getType()).newInstance();
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.setAccessible(true);
// field.set(model, entry.getValue());
// }
}
String code = action.execute(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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (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();
}
}
}
其他界面都没有做改动,和上面的是一样的
结果:
其他结果都是出得来的
3.5 使得框架的配置文件可变
只要修改中央控制器里的代码就行了
package com.zhoutubing.framework;
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 javax.swing.ActionMap;
import org.apache.commons.beanutils.BeanUtils;
/**
* 中央控制器
* 作用:接受请求,通过请求寻找处理请求的对应的子控器
* @author Administrator
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -3832035230274383463L;
// 在configModel对象中包含了所有的子控制器信息
private ConfigModel configModel;
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();
}
}
@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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(url);
try {
Action action = (Action)Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDrivern) {
ModelDrivern mdDrivern = (ModelDrivern) action;
// 此时的model所有属性值是null的
Object model = mdDrivern.getModel();
BeanUtils.populate(model, req.getParameterMap());
}
String code = action.execute(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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (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();
}
}
}
配置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>web05_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc3.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
在不改动framework文件里面的代码前提下,修改mvc.xml文件,如图,新建一个文件夹,复制framework里的mvc.xml文件
然后在改一个名字:
然后测试: