mvc框架的优化

本文介绍了如何优化MVC框架,通过XML配置替代硬编码,实现子控制器的反射实例化,增强代码的灵活性。文章还讨论了Action返回结果码用于自动跳转,并提出将一组相关操作整合到一个DispatcherAction中,利用反射调用方法,减少类的数量。此外,还引入了ModelDriver接口和反射工具类进行模型驱动,简化数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过XML对自定义mvc框架进行增强
在我的上一篇博客,实现了中央控制器根据不同的请求访问不同的子控制器类,不过有点麻烦点,子控制器需要在 ActionServlet中通过代码添加到Map<String, Action>中十分不方便,于是对mvc框架进行了优化。

** 1、 将Action的信息配置到xml(反射实例化)**
XML配置Action的信息,并进行反射实例化子控制器对象
像之前原来子控制器的来源是map集合,这样的话子控制器会被写死在map容器中,代码不够灵活
所以 现在将子控制器以配置的方式存放在config.xml中,未来可以通过改变config。xml中的内容
随意给中央控制器添加子控制器,增强代码的灵活性

ActionServlet			核心控制器
config.xml			子控制器(Action)配置
ForwardModel		Forward模型
ActionModel			Action模型
ConfigModel			Config模型 
ConfigModelFactory	ConfigModel工厂类(用于创建配置模型对象)

先把XML建模好

在这里插入图片描述
然后配置config.xml文件,配置子控制器(Action)

<?xml version="1.0" encoding="UTF-8"?>
	<!--
		config标签:可以包含0~N个action标签
	-->
<config>
	<action path="/cal" type="com.tzp.web.CalAction">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />
	</action>
</config>

在初始化方法中,解析XML,并读取配置文件
这样做的目的就是替换掉原来map集合,避免一个一个添加子控制器

public class DispatcherServlet extends HttpServlet{

	private ConfigModel configModel =null;
	
	public void init() {

		try {
			//将原有的读取框架的默认配置文件转变成可配置的路径的配置文件
			String xmlPath = this.getInitParameter("xmlPath");
			if(xmlPath==null||"".equals(xmlPath)) {
				configModel=ConfigModelFactory.build();
			}
			else {
				configModel=ConfigModelFactory.build(xmlPath);
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

那么又会一个新问题来了,每次跳转不过就是重定向和转发,这里做下修改,Action返回结果码,
配置文件自动给你做跳转。

/**
 * 子控制器
 *   专门来处理业务逻辑的
 * @author a
 *
 */

public interface Action {
	  String  excute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
	   
}

那结果码有什么呢?
结果码可以作为跳转的URL,比如:子控制器执行execute()后成功返回"calRes.jsp"

public class AddCalAction implements Action {

	@Override
	public String  excute(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路径。

那么问题又来了
一般我们对于某一张表进行增删查改操作,都会用一个Servlet来处理,但现在我们有AddAction、DelAction、ChengAction、ChuAction四个来处理,这样会造成类过多,现在我们进一步增强MVC框架,让对某一张表的增删查类操作放到同一个Action中。

增强3:将一组相关的操作放到一个Action中(反射调用方法) DispatcherAction
将一组相关的操作放到一个Action中,使用反射中的动态调用方法实现

先写一个模型驱动接口:

package com.tzp.framework;
/**
 * 模型驱动接口 是用来处理jsp界面传递过来的参数,
 * 将所有的参数自动封装到实体类T中
 * 
 *
 * @param <T>
 */
public interface ModelDriven<T> {
	T getModel();

}

对泛型类进行封装

package com.tzp.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.tzp.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();
		}

	}

}

子控制器

package com.tzp.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;

/**
 * 之前的Action只能处理一个实体类的业务、
 * 
 * 现在这个是增强版的子控制器
 * 凡是这个实体类的操作,对应方法都可以写在当前增强版的子控制器来完成
 * @author a
 *
 */
public class ActionSupprt implements Action{

	@Override
	//凡是被final修饰的方法都不能被重写
	public final String excute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String methodName = req.getParameter("methodName");
		String code=null;
		try {
			Method method = this.getClass().getDeclaredMethod(methodName, 
					HttpServletResponse.class,
					HttpServletRequest.class);
			method.setAccessible(true);
			//具体调用了你自己的所写的子控制器中的方法来处理浏览器请求
			code=(String) method.invoke(this, 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;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值