1. 什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
Model1 jsp+jdbc
Model2 ->MVC
核心思想:各司其职
2. MVC结构
V
jsp/ios/android
C
servlet/action
M
实体域模型(名词)
过程域模型(动词)
web 做浏览器请求分发
service 调用dao处理项目业务的
dao 操作数据库
注1:不能跨层调用
注2:只能出现由上而下的调用
3. 自定义MVC工作原理图
中央控制器(ActionServlet) 通过请求发出指令,命令对应的子控制器(Action)进行对请求的处理
中央控制器
中央控制器:查看是否有对应的子控制器来处理用户请求,如果就调用子控制器来处理请求;没有就报错,就处理不了请求
package com.qukang.framework;
import java.io.IOException;
import java.lang.reflect.Field;
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 com.qukang.web.Addction;
import com.qukang.web.Exceptaction;
import com.qukang.web.Minusction;
import com.qukang.web.Multiplication;
import com.sun.org.apache.xpath.internal.operations.Mult;
/**
* 中央控制器
* 作用:接受请求,通过请求的对应的子控制器
* @author VULCAN
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 5304895244625871732L;
// 一个子控制器的集合
private Map<String,Action> actionMap=new HashMap<>();
// 每次访问Servlet先执行init方法
public void init(){
actionMap.put("/addCal",new Addction());
actionMap.put("/delCal",new Minusction());
actionMap.put("/mluCal",new Multiplication());
actionMap.put("/excCal",new Exceptaction());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
init();
//拿到请求
String url=req.getRequestURI();
//比如 http://www.javaxl.com/login.jsp
//利用substring进行截取
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
//得到的是 /login
//再通过map集合根据键来取值,找到子控制器
Action action=actionMap.get(url);
//在调用子控制器子类的方法
action.execute(req, resp);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
子控制器
就是处理用户请求用的
package com.qukang.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:用来直接处理浏览器的请求
* @author VULCAN
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp);
}
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>T226_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
//将中央控制器配置到xml文件
<servlet-class>com.qukang.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
// 并将所有后缀为action结尾的请求进行处理
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
方法类通过实现子控制器接口实现对用户求情的处理
例如数学的加法:
package com.qukang.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qukang.entity.Cal;
import com.qukang.framework.Action;
public class Addction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp){
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("sum",cal.getNum1()+cal.getNum2());
req.getRequestDispatcher(" Demo.jsp").forward(req, resp);
return null;
}
}
JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/addCal.action" method="post">
num1<input type="text" name="num1" ><br>
num2<input type="text" name="num2" ><br>
<input type="submit" >
</form>
</body>
</html>
5.通过XML对自定义mvc框架进行增强
5.1 将Action的信息配置到xml(反射实例化)
将所有的子控制器都配置到mvc.xml配置文件中
当你mvc.xml文件没有配置好对应的子控制器
5.2 通过结果码控制页面的跳转
通过子控制器返回的结果码控制页面的调整
当你forword中没有写redirect属性时,运行项目时,你在做重定向界面时不加上req.getContextPath()拿到他的项目名,可能会包404错误,因为没有项目名,找不到!并且,重定向不是请求,可能拿不到结果!!!!
5.3 将一组相关的操作放到一个Action中(反射调用方法)
原因:普通的子控制器只能处理用户的一个请求,增强版的子控值能处理多个用户的请求
将mvc.xml中的所有action集合成一个,创建一个增强版的子控制器,再通过参数传过来的方法名进入子控值器进行方法用;
5.4 利用ModelDriver接口对Java对象进行赋值(反射读写属性)
作用:将jsp请求的所有参数自动封装到浏览器所要操作的实体类中
5.5 使得框架的配置文件可变
作用:解决框架配置文件冲突的问题
注1:Action多例模式?因为Action的属性要用来接收参数
所需要的jar包:
直接上代码:
工具类:
工厂(ConfigModelFactory)
package com.qukang.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();
}
}
}
用来描述mvc.xml配置文件中的config标签(ConfigModel)
package com.qukang.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);
}
}
用来描述mvc.xml配置文件中的action标签(ActionModel)
package com.qukang.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);
}
}
用来描述mvc.xml配置文件中的forward标签(ForwardModel)
package com.qukang.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;
}
}
mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- 加 -->
<!--
<action path="/addCal" type="com.qukang.web.Addction">
<forward name="rs" path="/Demo1.jsp" redirect="false" />
</action>
减
<action path="/delCal" type="com.qukang.web.Minusction">
<forward name="rs" path="/Demo1.jsp" redirect="false" />
</action>
乘
<action path="/mluCal" type="com.qukang.web.Multiplication">
<forward name="rs" path="/Demo1.jsp" redirect="false" />
</action>
除
<action path="/excCal" type="com.qukang.web.Exceptaction">
<forward name="rs" path="/Demo1.jsp" />
</action>
-->
<action path="/Cal" type="com.qukang.web.CalAction">
<forward name="rs" path="/Demo1.jsp" redirect="false" />
</action>
</config>
中央控制器
package com.qukang.framework;
import java.io.IOException;
import java.lang.reflect.Field;
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 com.qukang.web.Addction;
import com.qukang.web.Exceptaction;
import com.qukang.web.Minusction;
import com.qukang.web.Multiplication;
import com.sun.org.apache.xpath.internal.operations.Mult;
/**
* 中央控制器
* 作用:接受请求,通过请求的对应的子控制器
* @author VULCAN
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 5304895244625871732L;
// 在configModel对象中包含了所有的子控制器
private ConfigModel configModel;
// 一个子控制器的集合
private Map<String,Action> actionMap=new HashMap<>();
// 每次访问Servlet执行
public void init(){
// actionMap.put("/addCal",new Addction());
// actionMap.put("/delCal",new Minusction());
// actionMap.put("/mluCal",new Multiplication());
// actionMap.put("/excCal",new Exceptaction());
try {
String xmlPath=this.getInitParameter("xmlPath");
if(xmlPath==null ||"".equals(xmlPath)) {
configModel=ConfigModelFactory.newInstance();
}else {
configModel=ConfigModelFactory.newInstance(xmlPath);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 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);
ActionModel actionModel = configModel.get(url);
// 可能没有配置子控制器 所有我们需要抛一下子异常
if(actionModel ==null ) {
throw new RuntimeException("你没有配置action标签,找不到对应的子控制器");
}
try {
String type=actionModel.getType();
Action action=(Action)Class.forName(type).newInstance();
if(action instanceof ModelDrivern) {
ModelDrivern drivern=(ModelDrivern)action;
Object model = drivern.getModel();
// 将jsp传过来的参数封装到实体类中的原理原理
// 代码体现 源码
// 此时的model的所有属性值都是null
// 我们可以将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());
// }
// 前任插秧,后人舒服
BeanUtils.populate(model, req.getParameterMap());
// 大大的减轻了代码量
}
String execute = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(execute);
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 (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
模型驱动接口:
package com.qukang.framework;
/**
* 模型驱动接口
* 作用是将jsp所有传递过来的参数都自动封装到浏览器所要操作的实体类型中
* @author VULCAN
*
*/
public interface ModelDrivern<T> {
T getModel();
}
增强版的子控制器
package com.qukang.framework;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 增强版的子控制器
* 原来的子控制器只能处理一个用户的请求,有时候用户的请求时多个 ,但是都是操作同一张表,那么原有的子控制的代码编写繁琐
* 增强版的作用就是将
* 将一组的相关的操作放到一个Action中
* @author VULCAN
*
*/
public class ActionSupport implements Action {
@Override
public final String execute(HttpServletRequest req, HttpServletResponse resp) {
String methodName=req.getParameter("methodName");
String code ="";
try {
Method m=this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
code =(String) m.invoke(this,req,resp);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
}
return code;
}
}
处理增强版子控制器传来的所有请求:
下面是数学中的加减乘除的方法
package com.qukang.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qukang.entity.Cal;
import com.qukang.framework.ActionSupport;
import com.qukang.framework.ModelDrivern;
import com.sun.accessibility.internal.resources.accessibility;
public class CalAction extends ActionSupport implements ModelDrivern<Cal> {
private Cal cal=new Cal();
public String add(HttpServletRequest req, HttpServletResponse resp){
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("sum",cal.getNum1()+cal.getNum2());
return "rs";
}
public String min(HttpServletRequest req, HttpServletResponse resp){
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("sum",cal.getNum1()-cal.getNum2());
return "rs";
}
public String multip(HttpServletRequest req, HttpServletResponse resp){
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("sum",cal.getNum1()*cal.getNum2());
return "rs";
}
public String excep(HttpServletRequest req, HttpServletResponse resp){
// String num1=req.getParameter("num1");
// String num2=req.getParameter("num2");
// Cal cal=new Cal(Integer.valueOf(num1),Integer.valueOf(num2));
req.setAttribute("sum",cal.getNum1()/cal.getNum2());
return "rs";
}
@Override
public Cal getModel() {
// TODO Auto-generated method stub
return 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>
</head>
<script type="text/javascript">
function dopost(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=min";
}else if(num==3){
calForm.action="${pageContext.request.contextPath}/Cal.action?methodName=multip";
}else{
calForm.action="${pageContext.request.contextPath}/Cal.action?methodName=excep";
}
calForm.submit();
}
</script>
<body>
<form name="calForm" action="" method="post">
num1<input type="text" name="num1" ><br>
num2<input type="text" name="num2" ><br>
<button onclick="dopost(1)">+</button>
<button onclick="dopost(2)">-</button>
<button onclick="dopost(3)">*</button>
<button onclick="dopost(4)">/</button>
</form>
</body>
</html>
解决框架配置文件冲突的问题
<?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>T226_mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.qukang.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>
如果得到的xmlpath是控的就执行默认的newInstance()方法,如果不为空就执行带参的newInstance(xmlpath)方法
try {
String xmlPath=this.getInitParameter("xmlPath");
if(xmlPath==null ||"".equals(xmlPath)) {
configModel=ConfigModelFactory.newInstance();
}else {
configModel=ConfigModelFactory.newInstance(xmlPath);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}