一:什么是MVC
1.MVC全名是Model View Controller,是模型(model)-视图 (view)-控制器(controller)的缩写
2.它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
核心思想:各司其职
二: MVC结构
V : jsp/ios/android
C : servlet/action
M : 实体域模型(名词)— 过程域模型(动词)
jsp <% %>
web 做浏览器请求分发
service 调用dao处理项目业务的
dao 操作数据库
注1:不能跨层调用
注2:只能出现由上而下的调用**
三: 自定义MVC工作原理图
主控制动态调用子控制器调用完成具体的业务逻辑
(火车、控制台、车轨)
请求、主控制器、子控制器
四:自定义mvc解决的问题如下图
如图总结:
主控制器:
查看是否有对应的子控制器来处理用户请求,如果就调用子控制器来处理请求;没有就报错,就处理不了请求
子控制器:
就是处理用户请求用的
五:(简单)自定义MVC
1.cal 对象
package com.xwt.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() {}
public Cal(String num1, String num2) {
this.num1 = num1;
this.num2 = num2;
}
@Override
public String toString() {
return "Cal [num1=" + num1 + ", num2=" + num2 + "]";
}
}
2.DispatcherServlet中央控制器
package com.xwt.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 com.xwt.web.AddCalAction;
import com.xwt.web.ChengCalAction;
import com.xwt.web.ChuCalAction;
import com.xwt.web.DelCalAction;
/**
* 中央控制器
* 作用:
* 接受用户请求 通过用户请求的url寻找指定的子控制器去处理业务
* @author 婉婷宝贝
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
//存放action的容器
private Map<String, Action> actionMap=new HashMap<>();
public void init() {
//url是: http://localhost:8080/Mvc/cal_add.action
//uri是: /Mvc/cal_add.action
actionMap.put("/cal_add", new AddCalAction());//存放处理业务请求的所有控制器(是一个容器)
actionMap.put("/cal_del", new DelCalAction());
actionMap.put("/cal_cheng", new ChengCalAction());
actionMap.put("/cal_chu", 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 {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));//截取 /Mvc/cal_add.action
//AddCalAction action=(AddCalAction) actionMap.get(url);//得到AddCalAction子类
//Action a=(Action)action;//实现了action接口
Action action=actionMap.get(url);
action.execute(req, resp);
}
}
3.Action子控制器
package com.xwt.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 作用:
* 具体处理用户请求的类(实现了Action接口的类)
* @author 婉婷宝贝
*
*/
public interface Action {
/**
* 处理用户请求的方法
* @param req
* @param resp
* @return
*/
String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException;
}
4.实现子控制器 AddCalAction加法
package com.xwt.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.entity.Cal;
import com.xwt.framework.Action;
/**
* 实现子控制器
* AddCalAction加法
* 处理计算机加法业务类
* @author 婉婷宝贝
*
*/
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;
}
}
5.实现子控制器 DelCalAction减法
package com.xwt.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.entity.Cal;
import com.xwt.framework.Action;
/**
* 实现子控制器
* DelCalAction减法
* 处理计算机减法业务类
* @author 婉婷宝贝
*
*/
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;
}
}
6.实现子控制器 ChengCalAction乘法
package com.xwt.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.entity.Cal;
import com.xwt.framework.Action;
/**
* 实现子控制器
* ChengCalAction乘法
* 处理计算机乘法业务类
* @author 婉婷宝贝
*
*/
public class ChengCalAction 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;
}
}
7.实现子控制器 ChuCalAction除法
package com.xwt.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.entity.Cal;
import com.xwt.framework.Action;
/**
* 实现子控制器
* ChuCalAction除法
* 处理计算机除法业务类
* @author 婉婷宝贝
*
*/
public class ChuCalAction 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;
}
}
8.配置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.xwt.framework.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
9.实现加减乘除页面
<%@ 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>mvc</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";
}else if(v==3){
calForm.action="${pageContext.request.contextPath}/cal_cheng.action";
}else if(v==4){
calForm.action="${pageContext.request.contextPath}/cal_chu.action";
}
calForm.submit;//提交
}
</script>
</head>
<body>
<form id="calForm" 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>
10.结果页面rs
<%@ 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>结果集</title>
</head>
<body>
结果:${rs}
</body>
</html>
运行如下:
点 / 之后
页面计算机完成了
六:增强版(自定义MVC)
导入jar包
建模:
ActionModel 用来描述action标签
package com.xwt.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 用来描述config标签
package com.xwt.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);
}
}
ForwardModel 用来描述forward标签
package com.xwt.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;
}
}
ConfigModelFactory 工厂模式创建config建模对象
package com.xwt.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();
}
}
}
1.对存放控制器action容器的增强
DispatcherServlet 中央控制器
package com.xwt.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中央控制器
* 作用:
* 接受用户请求 通过用户请求的url寻找指定的子控制器去处理业务
* @author 婉婷宝贝
*
*1、对存放控制器action容器的增强
* 为什么要增强?
* 原来为了完成业务需求 需要不断修改框架的代码 这样设计是不合理的
* 处理方式:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
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);
try {
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
action.execute(req, resp);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal_add" type="com.xwt.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.xwt.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_cheng" type="com.xwt.web.ChengCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_chu" type="com.xwt.web.ChuCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
运行cal.jsp
第一步增强成功
2.处理结果码的跳转形式
目的:达到简化代码的结果
修改 AddCalAction(其他的都一样就不一一示范了)
package com.xwt.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.entity.Cal;
import com.xwt.framework.Action;
/**
* 实现子控制器
* AddCalAction加法
* 处理计算机加法业务类
* @author 婉婷宝贝
*
*/
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 "rs";
}
}
DispatcherServlet 中央控制器
package com.xwt.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中央控制器
* 作用:
* 接受用户请求 通过用户请求的url寻找指定的子控制器去处理业务
* @author 婉婷宝贝
*
*1、对存放控制器action容器的增强
* 为什么要增强?
* 原来为了完成业务需求 需要不断修改框架的代码 这样设计是不合理的
* 处理方式:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
*
*2、处理结果码的跳转形式
* 达到简化代码的结果
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
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);
try {
if(actionModel==null) {
throw new RuntimeException("您没有配置指定的子控制器来处理用户请求");
}
Action 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(forwardModel.getPath());
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal_add" type="com.xwt.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.xwt.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<!-- <action path="/cal_cheng" type="com.xwt.web.ChengCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action> -->
<action path="/cal_chu" type="com.xwt.web.ChuCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
照样可以运行
如果此时我再调用我注释的乘法将会温馨提示:
3.将一组操作一个子控制器去完成
ActionSupport 增强版的子控制器
package com.xwt.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 婉婷宝贝
*
*/
public class ActionSupport implements Action{
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从前台传递需要调用的方法名到后台 实现动态方法调用
String methodName=req.getParameter("methodName");
//思考 怎么获取 CalAction calaction =new CalAction();
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 e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
return code;
}
}
CalAction
package com.xwt.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.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()));
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()));
return "rs";
}
public String cheng(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()));
return "rs";
}
public String chu(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()));
return "rs";
}
}
mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.xwt.framework.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
更改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>mvc</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.action="${pageContext.request.contextPath}/cal.action?methodName=del";
}else if(v==3){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=cheng";
}else if(v==4){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=chu";
}
calForm.submit;//提交
}
</script>
</head>
<body>
<form id="calForm" 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.处理jsp传递到后台的参数封装
定义一个接口:ModelDriven
package com.xwt.framework;
/**
* 模型驱动接口
* 作用:
* 给对应处理业务的子控制器中包含的实体类进行jsp参数封装
* @author 婉婷宝贝
*
*/
public interface ModelDriven<T> {
T getModel();
}
更改 CalAction
package com.xwt.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xwt.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 {
req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
return "rs";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
return "rs";
}
public String cheng(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
return "rs";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
return "rs";
}
@Override
public Cal getModel() {
// TODO Auto-generated method stub
return cal;
}
}
更改中央控制器 DispatcherServlet
package com.xwt.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寻找指定的子控制器去处理业务
* @author 婉婷宝贝
*
*1、对存放控制器action容器的增强
* 为什么要增强?
* 原来为了完成业务需求 需要不断修改框架的代码 这样设计是不合理的
* 处理方式:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
*
*2、处理结果码的跳转形式
* 达到简化代码的结果
*
*3、将一组操作一个子控制器去完成
*
*4、处理jsp传递到后台的参数封装
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
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);
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(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
5:解决框架配置文件重名冲突问题
更改中央控制器 DispatcherServlet
package com.xwt.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寻找指定的子控制器去处理业务
* @author 婉婷宝贝
*
*1、对存放控制器action容器的增强
* 为什么要增强?
* 原来为了完成业务需求 需要不断修改框架的代码 这样设计是不合理的
* 处理方式:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
*
*2、处理结果码的跳转形式
* 达到简化代码的结果
*
*3、将一组操作一个子控制器去完成
*
*4、处理jsp传递到后台的参数封装
*
*5、解决框架配置文件重名冲突问题
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
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);
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(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
运行如下图:
搞出配置文件重名冲突问题
写入一样的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.xwt.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/you.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
运行如下: