自定义MVC_2
本人在自定义MVC_1中实现了中央控制器根据不同的请求访问不同的子控制器类,但有个问题:子控制器需要在 ActionServlet中通过代码添加到Map<String, Action>中十分不方便,于是我们对自定义MVC框架进行增强。。。
增强1:通过XML对自定义mvc框架进行增强
通过XML配置Action的信息,并通过反射实例化Action子控制器实现类对象。
需要复制文件到项目(XML建模 + DOM4J解析 + 反射技术)
ActionServlet 核心控制器
config.xml Action配置
ForwardModel Forward模型
ActionModel Action模型
ConfigModel Config模型
ConfigModelFactory ConfigModel工厂类(用于创建配置模型对象)
创建ForwardModel、创建ActionModel、创建ConfigModel、创建ConfigModelFactory、config.xml文件
在src下创建config.xml文件,用于Action的配置:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.xzy.web.CalAction">
<forward name="calRes" path="/calRes.jsp" redirect="false" />
</action>
……
</config>
在init()中初始化加载、解析XML
作用:替代Map<String, Action>代码
private ConfigModel configModel;
public void init() {
try {
//将原有的读取框架默认配置文件转变成读取可配置路径的配置文件
String xmlPath = this.getInitParameter("xmlPath");
if(xmlPath == null || "".equals(xmlPath))
configModel = ConfigModelFactory.build();
else {
configModel = ConfigModelFactory.build(xmlPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
问题:每个Action在执行完后都会做跳转动作,跳转无非就是重定向或转发,这里进行强化,Action只返回一个结果码,配置文件自动给你做跳转。
增强2: 通过结果码控制页面的跳转
什么是结果码?
ActionServlet的doPost()方法中最后将请求委托给子控制器Action后,Action的子类中的execute()执行完后会返回一个String字符串给ActionServlet,返回的这个String字符串,就称为“结果码”。
package com.xzy.framework;
/**
* 子控制器 专门用来处理业务逻辑的
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
结果码有什么用?
结果码可以作为跳转的URL,比如:子控制器执行execute()后成功返回"calRes.jsp"。
package com.xzy.web;
import java.io.IOException;
import javax.servlet.ServletException;
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");
req.setAttribute("res", Integer.valueOf(num1) + Integer.valueOf(num2));
// req.getRequestDispatcher("calRes.jsp").forward(req, resp);
return "calRes";
}
}
也可以作为一个编码,与XML配置中中的name进行匹配,跳转到path路径。
<forward name="calRes" path="/calRes.jsp" redirect="false" />
问题:一般我们针对某一张表进行CRUD操作,都会用一个Servlet来处理,但现在我们有AddAction、DelAction、ChengAction、ChuAction四个来处理,这样会造成文件过多,现在我们进一步增强MVC框架,让对某张表的CRUD操作放到同一个Action中。
增强3:将一组相关的操作放到一个Action中(反射调用方法) DispatcherAction
将一组相关的操作放到一个Action中,使用反射中的动态调用方法实现
DispatcherAction
String methodName = req.getParameter(“methodName”);
methodName:add/minus/mul/div
CalAction extends DispatcherAction
先写一个模型驱动接口:
package com.xzy.framework;
/**
* 模型驱动接口 是用来处理jsp界面传递过来的参数,
* 将所有的参数自动封装到实体类T中
*
*
* @param <T>
*/
public interface ModelDriven<T> {
T getModel();
}
对泛型类进行封装
package com.xzy.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xzy.entity.Cal;
import com.xzy.framework.ActionSupport;
import com.xzy.framework.ModelDriven;
public class CalAction extends ActionSupport implements ModelDriven<Cal> {
private Cal cal = new Cal();
// @Override
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String num1 = req.getParameter("num1");
// String num2 = req.getParameter("num2");
req.setAttribute("res", Integer.valueOf(cal.getNum1()) + Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("calRes.jsp").forward(req, resp);
return "calRes";
}
// 减
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.valueOf(cal.getNum1()) - Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("calRes.jsp").forward(req, resp);
return "calRes";
}
// 乘
public String cheng(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.valueOf(cal.getNum1()) * Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("calRes.jsp").forward(req, resp);
return "calRes";
}
// 除
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.valueOf(cal.getNum1()) / Integer.valueOf(cal.getNum2()));
// req.getRequestDispatcher("calRes.jsp").forward(req, resp);
return "calRes";
}
@Override
public Cal getModel() {
return cal;
}
}
利用ModelDriver接口对Java对象进行赋值(反射读写方法)
BeanUtils.populate(calBean, parameterMap);
ModelDriver接口返回的对象不能为空
导入反射工具类
commons-beanutils-1.8.0.jar
commons-logging.jar
作用:动态取值(获取表单数据)。
总共的核心代码如下:
中央控制器
package com.xzy.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;
/**
* 中英控制器
*
*/
public class DispatchServlet extends HttpServlet {
private static final long serialVersionUID = -3994738601338360591L;
// private Map<String, Action> actionMap = new HashMap<>();
private ConfigModel configModel;
public void init() {
try {
// 将原有的读取框架默认配置文件转变成读取可配置路径的配置文件
String xmlPath = this.getInitParameter("xmlPath");
if (xmlPath == null || "".equals(xmlPath))
configModel = ConfigModelFactory.build();
else {
configModel = ConfigModelFactory.build(xmlPath);
}
} 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 {
init();
//
String url = req.getRequestURI();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
// Action action = actionMap.get(url);
// action.execute(req, resp);
ActionModel actionModel = configModel.pop(url);
if (actionModel == null) {
throw new RuntimeException("你没有配置对应的子控制器Action!!!");
}
// 通过全路径名获取到类对象,进行实例化,调用函数
try {
// 原来控制器的来源是map集合,这样的话子控制器会被写在map容器中,代码不够灵活
// 现在将子控制器以配置的方式存放在config.xml中,未来可以通过改变config.xml中的内容
// 随意给中英控制器添加子控制器
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
// 调用模型驱动接口,获取所要操作的实体类,然后将jsp传递过来的参数,封装到实体类中
if (action instanceof ModelDriven) {
ModelDriven modelDriven = (ModelDriven) action;
Object model = modelDriven.getModel();
// Map<String, String[]> map = req.getParameterMap();
// for(Map.Entry<String, String[]> entry: map.entrySet()){
可以获取到类对应的属性,bname,获取到类对应的属性值
// }
// 将所有的参数自动封装到实体类T中
BeanUtils.populate(model, req.getParameterMap());
}
// 每个子控制器都需要对结果进行处理,也就是说要么转发,要么重定向,代码重复量较大
// 针对于这一现象,将其交给配置文件来处理
// 调用了增强版的自控制器来处理业务逻辑
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(code);
if (forwardModel == null) {
throw new RuntimeException("你没有配置对应的子控制器Action的处理方式ForwardModel~~~~~~~~~~~·!");
}
String jspPath = forwardModel.getPath();
if (forwardModel.isRedirect()) {
resp.sendRedirect(req.getContextPath() + jspPath);
} else {
req.getRequestDispatcher(jspPath).forward(req, resp);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
子控制器
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;
/**
* 之前的Action只能处理一个实体类的一个业务
*
* ActionSupport: 这个是增强版的子控制器 凡是这个实体类的操作,对应方法都可以写在当前增强版的子控制器来完成
* ` */
public class ActionSupport implements Action {
@Override
// 凡是被final修饰的方法都不需要被重写
public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String methodName = req.getParameter("methodName");
//声明返回值
String code = null;
try {
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
HttpServletResponse.class);
method.setAccessible(true);
// 具体调用了你自己所写的子控制器中的方法来处理浏览器请求
code = (String) method.invoke(this, req, resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return code;
}
}`
(泛型)模型驱动接口
package com.xzy.framework;
/**
* 模型驱动接口 是用来处理jsp界面传递过来的参数,
* 将所有的参数自动封装到实体类T中
*
*
* @param <T>
*/
public interface ModelDriven<T> {
T getModel();
}