自定义MVC
1. 什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
Model1 jsp+jdbc
Model2 ->MVC
核心思想:各司其职
2. MVC结构
V
jsp/ios/android
C
servlet/action
M
实体域模型(名词)
过程域模型(动词)
注1:不能跨层调用
注2:只能出现由上而下的调用
3. 自定义MVC工作原理图
解释:
浏览器(请求)–》ActionServlet(中央控制器)–》Action(子控制器)
需要导的jar包:
Cal实体类:
package com.wangjing.entity;
public class Cal {
private String num1;
private String num2;
public String getNum1() {
return num1;
}
public void setNum1(String num1) {
this.num1 = num1;
}
public String getNum2() {
return num2;
}
public void setNum2(String num2) {
this.num2 = num2;
}
@Override
public String toString() {
return "Cal [num1=" + num1 + ", num2=" + num2 + "]";
}
public Cal(String num1, String num2) {
super();
this.num1 = num1;
this.num2 = num2;
}
public Cal() {
super();
}
}
CalAction类,主要是写方法:
package com.wangjing.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wangjing.entity.Cal;
import com.wangjing.framework.ActionSupport;
import com.wangjing.framework.ModeDriven;
public class CalAction extends ActionSupport implements ModeDriven<Cal>{
private Cal cal=new Cal();
/**
* 加
*/
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String num1 = req.getParameter("num1");
// String num2 = req.getParameter("num2");
// Cal cal = new Cal(num1,num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
/**
* 减
*/
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String num1 = req.getParameter("num1");
// String num2 = req.getParameter("num2");
// Cal cal = new Cal(num1,num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
/**
* 乘
*/
public String aaa(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String num1 = req.getParameter("num1");
// String num2 = req.getParameter("num2");
// Cal cal = new Cal(num1,num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
/**
* 除
*/
public String bbb(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String num1 = req.getParameter("num1");
// String num2 = req.getParameter("num2");
// Cal cal = new Cal(num1,num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
@Override
public Cal getModel() {
return cal;
}
}
ActionModel类供set和get方法:
package com.wangjing.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);
}
}
ConfigModelFactory,工厂模式创建config建模对象:
package com.wangjing.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, 用来描述forward标签
package com.wangjing.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;
}
}
Action,子控制器:
package com.wangjing.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器:
* 作用:具体处理用户请求的类(实现了Action接口的类)
* @author wj
*
*/
public interface Action {
String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException;
}
ActionSupport,增强版的控制器
package com.wangjing.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;
/**
* 增强版的控制器
* 作用:将一组操作放到一个字控制器去完成
* @author wj
*
*/
public class ActionSupport implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从前台传递需要调用的方法名到后台,实现动态方法调用
String menthodName = req.getParameter("menthodName");
String code = null;
// 思考:
try {
Method m = this.getClass().getDeclaredMethod(menthodName, HttpServletRequest.class,HttpServletResponse.class);
// 打开访问权限
m.setAccessible(true);
code = (String) m.invoke(this, req,resp);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return code;
}
}
DispatcherServlet,主控制器
package com.wangjing.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 org.apache.commons.beanutils.BeanUtils;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过请求的URL寻找指定的子控制器去处理业务
*
* 1.对存放子控制器action容器的增强
* 为什么要增强:原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的
* 处理方式:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
*
*
* 2.处理结果码的跳转形式
* 达到简化代码的目的
*
* 3.将一组操作放到一个字控制器去完成
*
*
* 4.处理jsp传递到后台的参数封装
*
* 5.解决框架配置文件名冲突问题
* @author wj
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 7355939424921732064L;
// private Map<String, Action> actionMap=new HashMap<String, Action>();
private ConfigModel configModel = null;
public void init() {
// actionMap.put("/cal_add", new AddCalAction());
// actionMap.put("/cal_del", new DelCalAction());
// actionMap.put("/cal_aaa", new AaaCalAction());
// actionMap.put("/cal_bbb", new BbbCalAction());
try {
String mvcXmlLocation = this.getInitParameter("mvcXmlLocation");
if(null == mvcXmlLocation || "".equals("mvcXmlLocation")) {
mvcXmlLocation = "mvc.xml";
}
System.out.println("mvcXmlLocation:"+mvcXmlLocation);
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 {
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);
try {
if(actionModel == null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModeDriven) {
ModeDriven modeDriven = (ModeDriven) action;
Object model= modeDriven.getModel();
// 给model赋值了,那么意味着在调用add/del方法的时候cal不在是空的了
BeanUtils.populate(model, req.getParameterMap());
}
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if("false".equals(forwardModel.getRedirect())) {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else {
// 主意:默认会缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
mvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- <action path="/cal_add" type="com.wangjing.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.wangjing.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_aaa" type="com.wangjing.web.AaaCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_bbb" type="com.wangjing.web.BbbCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> -->
<!-- 3.将一组操作放到一个字控制器去完成 -->
<action path="/cal" type="com.wangjing.web.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
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>mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.wangjing.framework.DispatcherServlet</servlet-class>
<!-- 当有同名的xml文件时,可以采用 ,没有重名时就注销 使用默认的 -->
<!-- <init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/wang.xml</param-value>
</init-param> -->
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
ModeDriven:
package com.wangjing.framework;
/**
* 模型驱动接口
* 作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
* @author wj
*
* @param <T>
*/
public interface ModeDriven<T> {
T getModel();
}
cal,显示页面:
<%@ 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(v) {
if(v==1){
calForm.action="${pageContext.request.contextPath }/cal.action?menthodName=add";
}else if (v==2) {
calForm.action="${pageContext.request.contextPath }/cal.action?menthodName=del";
}else if (v==3) {
calForm.action="${pageContext.request.contextPath }/cal.action?menthodName=aaa";
}else if (v==4) {
calForm.action="${pageContext.request.contextPath }/cal.action?menthodName=bbb";
}
calForm.submit();
}
</script>
</head>
<body>
<form id="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>
显示结果: