自定义MVC——2

7 篇文章 0 订阅
5 篇文章 0 订阅

今天讲的是MVC优化版~

在上篇博客自定义MVC——1中已经实现了简易的计算机操作,但是有些代码可以更加优化,并且作用性更强的。接下来要通过XML对自定义mvc框架进行增强。

将Action运用到XML

首先在Dispatchersevlet中的init()方法中,原有的

actionMap.put("/addCal",new AddCalAction());
actionMap.put("/delCal",new DelCalAction());
actionMap.put("/chenCal",new ChenCalAction());
actionMap.put("/chuCal",new ChuCalAction());

这种方法把路径写死了,不方便,
所有改成使用Action来写,运用工厂模式,可以从XML里面进行配置,

public void init() {
		try {
			
				configMode = ConfigModelFactory.newInstance();
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

2,跳转调整

原有的跳转是通过servlet重定向或者转发完成的,但这样就出现一个问题,每个servlet都得写着一句,所有有些繁琐,这也是可以优化的:
1,首先在每一个servlet方法中,将方法返回值改为String,返回的是要跳转或者重定向的路径 。例(增加):

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));
		return "calRes";
	}

2,通过Action工厂模式获得redirect,获得这个判断是否重定向,
然后在Dispatchersevlet中进行判断,true代表重定向,false代表转发。

			String jsppath = forwardModel.getPath();
			if(!"false".equals(forwardModel.getRedirect())) {
				resp.sendRedirect(req.getContextPath()+jsppath);
			}
			else {
				req.getRequestDispatcher(jsppath).forward(req, resp);
			}	

3,反射调用方法

现在这种情况,servlet要根据需求来操作的话,要写很多个servlet,所有对于这个也是可以强化一下的:

1,之前的Action 只能处理一个实体类的一个业务,现在要写一个增强版的Action,凡是这个实体类的操作,对应的方法都可以写在当前增强版的子控制器来完成。


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 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 (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		
		return code;
	}
}

返回的则是跳转或者重定向的路径。

2,然后创建一个专门处理事务的类,CalAction,所有的操作都由这个类来解决。

package com.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;

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");
		 req.setAttribute("res", Integer.valueOf(num1)+Integer.valueOf(num2));
		return "calRes";
	}
	
	public String del(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));
		return "calRes";
	}
	
	public String chen(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));
		return "calRes";
	}
	
	public String chu(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));
		return "calRes";
	}

}

然后在Dispatchersevlet中获取:

			String code = action.execute(req, resp);
			ForwardModel forwardModel = actionModel.get(code);

大概思路就是:首先通过XML解析获得Cal.jsp要进入的action,通过这个路径获得类对象,然后通过这个类对象继承了的ActionSupport的execute方法传过来的req获得参数,通过这个参数可以知道进行调用哪个方法。然后返回路径code。通过这个路径code获得返回路径:

	<forward name="calRes" path="calRes.jsp" redirect="false" />
		<forward name="success" path="/main.jsp" redirect="true" />
	</action>

4,使参数进行自动封装

在处理事务界面,每个参数都得自己获取,这有些麻烦,能否让这些参数自动封装然后调用呢?

1,首先建立一个模型驱动接口,用来处理JSP页面传递过来的参数,将所有的参数自动封装到实体类T中:

public interface ModelDriven<T> {
	T getMoadel ();
}

2,在处理界面实现这个接口,然后实例化一个对象,:

package com.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zking.entity.Cal;
import com.zking.framework.ActionSupport;
import com.zking.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");
		 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 {
//		 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 chen(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 chu(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";
	}

	@Override
	public Cal getMoadel() {
		return cal;	
	}
	
}

通过这个对象进行赋值,一开始对象里肯定是没值的,那么怎么给这个对象先赋值呢?可以通过Dispatchersevlet来赋值:

if(action instanceof ModelDriven) {
				ModelDriven Modeldriven = (ModelDriven)action;
				//获得对象
				Object model = Modeldriven.getMoadel();
				
//				Map<String, String[]> map = req.getParameterMap();
//				for(Map.Entry<String, String[]> entry : map.entrySet()) {
//					//可以获取到类对应的属性bname,获取到类所对应的属性值;
//				}
				//将所有的参数自动封装到实体类T中
				BeanUtils.populate(model, req.getParameterMap());
			}

5,使得框架的配置文件可变

在原先的init()中,configMode = ConfigModelFactory.newInstance();是写死的,不方便更换XML文件,所有这样也是可以加工加强的:

在加工厂中,定义两个方法即可:
一个有参一个无参,无参调用有参


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();
		}
	}
}
public void init() {
		try {
			//将原有的读取框架的默认配置文件转变成可配置路径的配置文件
			String xmlPath = this.getInitParameter("xmlPath");
			if(xmlPath ==null||"".equals(xmlPath)) {
				configMode = ConfigModelFactory.newInstance();
			}else {
				configMode = ConfigModelFactory.newInstance(xmlPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

这就是建议的自定义MVC框架,有什么疑问可以下方留言或者联系本人。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值