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:只能出现由上而下的调用
自定义MVC工作原理图
主控制动态调用子控制器调用完成具体的业务逻辑
导入架包:
然后再写入五个工具类。
ActionModel:
package com.lx.framework;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @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.lx.framework;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @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);
}
}
ConfigModelFatory:
package com.lx.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");
}
/**
*
* @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.lx.framework;
import java.io.Serializable;
/**
* @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>
1.将Action的信息配置到xml(反射实例化):
xml:
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<!-- <action path="/cal_add" type="com.lx.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.lx.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> -->
<action path="/cal" type="com.lx.web.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
主控制器:
package com.lx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeErrorException;
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.lx.web.AddCalAction;
public class DispatherServlet extends HttpServlet{
private static final long serialVersionUID = -6950857797935097968L;
// private Map<String, Action> actionMap=new HashMap<String, Action>();
private ConfigModel configModel =null;
public void init() {
// actionMap.put("/cal_add", new AddCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// AddCalAction action = (AddCalAction) actionMap.get(url);
// Action a=(Action)action;
// 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 ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
//req.getParameterMap();//封装了所有前台的键值对
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(forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.通过结果码控制页面的跳转 把子控制器的跳转全部写到主控制器中
子控制器:
package com.lx.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lx.entity.Cal;
import com.lx.framework.Action;
public class AddCalAction implements Action {
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 "rs";
}
}
主控制器
package com.lx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeErrorException;
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.lx.web.AddCalAction;
public class DispatherServlet extends HttpServlet{
private static final long serialVersionUID = -6950857797935097968L;
// private Map<String, Action> actionMap=new HashMap<String, Action>();
private ConfigModel configModel =null;
public void init() {
// actionMap.put("/cal_add", new AddCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// AddCalAction action = (AddCalAction) actionMap.get(url);
// Action a=(Action)action;
// 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 ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
//req.getParameterMap();//封装了所有前台的键值对
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(forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.将一组相关的操作放到一个Action中(反射调用方法)
定义一个ActionSupport类
package com.lx.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;
public class ActionSupport implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// 从前台传递需要掉用的方法名到后台,实现动态方法调用
String methodName = req.getParameter("methodName");
String code=null;
try {
Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
code = (String) m.invoke(this, req,resp);
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
}
在定义一个CalAction类
package com.lx.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lx.entity.Cal;
import com.lx.framework.ActionSupport;
import com.lx.framework.ModelDriven;
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() {
// TODO Auto-generated method stub
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>
<script type="text/javascript">
function doSub(v) {
if(v==1){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=add";
}else if(v==2){
calForm.acthion="${pageContext.request.contextPath}/cal.action?methodName=del";
}else if(v==3){
calForm.acthion="${pageContext.request.contextPath}/cal.action?methodName=c";
}else if(v==4){
calForm.acthion="${pageContext.request.contextPath}/cal.action?methodName=cf";
}
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>
4.利用ModelDriver接口对Java对象进行赋值(反射读写方法)
定义一个ModelDriven接口
package com.lx.framework;
public interface ModelDriven<T> {
T getModel();
}
CalAction类
package com.lx.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lx.entity.Cal;
import com.lx.framework.ActionSupport;
import com.lx.framework.ModelDriven;
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() {
// TODO Auto-generated method stub
return null;
}
}
主控制器
package com.lx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeErrorException;
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.lx.web.AddCalAction;
public class DispatherServlet extends HttpServlet{
private static final long serialVersionUID = -6950857797935097968L;
// private Map<String, Action> actionMap=new HashMap<String, Action>();
private ConfigModel configModel =null;
public void init() {
// actionMap.put("/cal_add", new AddCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// AddCalAction action = (AddCalAction) actionMap.get(url);
// Action a=(Action)action;
// 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 ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
//req.getParameterMap();//封装了所有前台的键值对
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(forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5 使得框架的配置文件可变
主控制器
package com.lx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeErrorException;
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.lx.web.AddCalAction;
public class DispatherServlet extends HttpServlet{
private static final long serialVersionUID = -6950857797935097968L;
// private Map<String, Action> actionMap=new HashMap<String, Action>();
private ConfigModel configModel =null;
public void init() {
// actionMap.put("/cal_add", new AddCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// AddCalAction action = (AddCalAction) actionMap.get(url);
// Action a=(Action)action;
// 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 ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model=modelDriven.getModel();
//给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
//req.getParameterMap();//封装了所有前台的键值对
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(forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
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>lx_mvc</display-name>
<servlet>
<servlet-name>dispatherServlet</servlet-name>
<servlet-class>com.lx.framework.DispatherServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>