自定义MVC
1. 什么是MVC
- MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写, 它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
- 核心思想:各司其职
2. MVC结构
- M 实体域模型(名词), 过程域模型(动词)
- V jsp/ios/android
- C servlet/action
3. 自定义MVC工作原理图
4.项目的各个包以及使用到的jar包
jar包链接:https://pan.baidu.com/s/1L4JXURuMP7bRaKaIC-bhEA
提取码:gv0z
5.案例:用MVC写一个加减乘除
实体类:
Cal:
package 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;
}
public Cal(String num1, String num2) {
super();
this.num1 = num1;
this.num2 = num2;
}
public Cal() {
super();
}
@Override
public String toString() {
return "Cal [num1=" + num1 + ", num2=" + num2 + "]";
}
}
显示界面:
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(v){
if(v==1){
calForm.action="${pageContext.request.contextPath}/cal_add.action";
}else if(v==2){
calForm.action="${pageContext.request.contextPath}/cal_del.action";
}
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>
</form>
</body>
</html>
rs.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>
结果:${rs }
</body>
</html>
web类:
增加:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.page.framework.Action;
import entity.Cal;
public class AddCalAction implements Action {
@Override
public String execute(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 null;
}
}
删除:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.page.framework.Action;
import entity.Cal;
public class DelCalAction implements Action {
@Override
public String execute(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 null;
}
}
工具类:
ActionModel
package com.su.beike;
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.su.beike;
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.su.beike;
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("config.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.su.beike;
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标签:可以包含0~N个action标签
-->
<config>
<!--
action标签:可以饱含0~N个forward标签
path:以/开头的字符串,并且值必须唯一 非空
type:字符串,非空
-->
<action path="/regAction" type="test.RegAction">
<!--
forward标签:没有子标签;
name:字符串,同一action标签下的forward标签name值不能相同 ;
path:以/开头的字符串
redirect:只能是false|true,允许空,默认值为false
-->
<forward name="failed" path="/reg.jsp" redirect="false" />
<forward name="success" path="/login.jsp" redirect="true" />
</action>
<action path="/loginAction" type="test.LoginAction">
<forward name="failed" path="/login.jsp" redirect="false" />
<forward name="success" path="/main.jsp" redirect="true" />
</action>
<action path="/calAction" type="com.zking.web.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
- 第一种(Action的动态配置):
代码如下:
DispatcherServlet(主控制器):
package com.page.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;
/**
* 主控制器
* @author 86182
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -6002796367086712483L;
private ConfigModel configModel = null;
public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
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("."));
ActionModel actionModel=configModel.get(url);
Action action;
try {
action = (Action) Class.forName(actionModel.getType()).newInstance();
action.execute(req, resp);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Action(子控制器):
package com.page.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器:
* 作用:具体处理用户请求的类 (实现了Action接口的类)
* @author Administrator
*
*/
public interface Action {
String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException;
}
- 第二种(子控制器返回码的处理):
ActionModel:
package com.page.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;
/**
* 主控制器
* @author 86182
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -6002796367086712483L;
private ConfigModel configModel = null;
public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
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("."));
ActionModel actionModel=configModel.get(url);
Action action;
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
action = (Action) Class.forName(actionModel.getType()).newInstance();
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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
将AddCalAction和DelCalAction中return返回一个rs
输入一个无效链接:
- 第三种(增强子控制器):
ActionSupport:
package com.page.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 Administrator
*增强版的子控制器
*作用:
* 将一组操作放到一个子控制器去完成
*/
public class ActionSupport implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从前台传递需要调用的方法名到后台,实现动态方法调用
String methodName=req.getParameter("methodName");
String code=null;
try {
Method m=this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
try {
code=(String) m.invoke(this, req,resp);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
}
web类中CalAction:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.page.framework.ActionSupport;
import entity.Cal;
public class CalAction extends ActionSupport{
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";
}
}
mvc.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.web.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
jsp界面的变动:
<script type="text/javascript">
function doSub(v){
if(v==1){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=add";
}else if(v==2){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=del";
}
calForm.submit();
}
</script>
- 第四种(jsp参数封装增强):
DispatcherServlet:
package com.page.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;
/**
* 主控制器
* @author 86182
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -6002796367086712483L;
private ConfigModel configModel = null;
public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
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("."));
ActionModel actionModel=configModel.get(url);
Action action;
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
action = (Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add,del方法的时候cal不再为空了
req.getParameterMap();
try {
BeanUtils.populate(model, req.getParameterMap());
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ActionSupport:
package com.page.framework;
/**
* @author Administrator
*
* @param <T>
* 模型驱动接口
* 作用:对应处理业务的子控制器中包含的实体类进行jsp参数封装
*/
public interface ModelDriven<T> {
T getModel();
}
CalAction:
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.page.framework.ActionSupport;
import com.page.framework.ModelDriven;
import entity.Cal;
public class CalAction extends ActionSupport implements ModelDriven<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";
}
@Override
public Cal getModel() {
return cal;
}
}
- 第五种(框架配置文件可变):
新建一个文件夹copy一个mvc.xml进去:
DispatcherServlet:
package com.page.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;
/**
* 主控制器
* @author 86182
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -6002796367086712483L;
private ConfigModel configModel = null;
public void init() {
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) {
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("."));
ActionModel actionModel=configModel.get(url);
Action action;
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的子控制器来处理用户请求");
}
action = (Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add,del方法的时候cal不再为空了
req.getParameterMap();
try {
BeanUtils.populate(model, req.getParameterMap());
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
增加web.xml的配置文件:
<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/xiao.xml</param-value>
</init-param>
运行结果:
在web.xml中注释
<--<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/xiao.xml</param-value>
</init-param> -->
运行结果显示为默认的: