自定义mvc的增强

自定义mvc的增强

根据上一篇博客简单的自定义mvc 这篇博客我们对上一篇博客的自定义mvc进行了一个增强

下面我们对自定义mvc增加进行一个分析
1.首先我们需要四个架包,其次我们需要对子控制器进行增强,再次我们需要将子控制器配置xml文件,我们还需要判断转发类型,false或者true 判断他是否需要重定向或者转发。
2.我们还需要定义一个泛型接口;通过接口进行一个属性判断

其次是四个夹包,可以去网上进行下载
如下四个:

在这里插入图片描述

接着我们来看代码

控制器

控制器分两种,一个是子控制器,一个是主控制器,下面我们来看看他们的作用 吧
子控制器
子控制器的作用就是
专门用来处理业务逻辑的
用你写的类来增强子控制器,就能处理所有的业务逻辑
我们来看代码;
我们要用子控制器将接口Action的信息反射:

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

	
}

中央控制器
接着就是中央控制器
这个中央控制器说起来比较麻烦:不如来看代码吧:
基本每一行都会有注释,不了解的可以看一下

public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	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);
			}
			configModel = ConfigModelFactory.build();
		} 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("."));
		
	
		ActionModel actionModel = configModel.pop(url);
		
		if(actionModel == null) {
			throw new RuntimeException("没有配置对应的子控制器 Action");
		}
		
		/**
		 * 将Action的信息配置到xml(反射实例化)
		 * 
		 * 原来子控制器的来源是map集合,如此,子控制器就被写死在map容器中,代码不灵活
		 * 现将子控制器以配置的方式存在config.xml中,即通过改变config.xml中的内容给中央控制器添加子控制器
		 */
		
		try {
			Action action = (Action)Class.forName(actionModel.getType()).newInstance();
			
		
			
			if(action instanceof ModelDriven) {
				ModelDriven modelDriven = (ModelDriven) action;//CalAction向上提升为ModelDriven
				Object model = modelDriven.getModel();
				
		
				Map<String, String[]> map = req.getParameterMap();
				for (Map.Entry<String, String[]> entry : map.entrySet()) {
				
				}
				
			
				BeanUtils.populate(model, req.getParameterMap());
			}
	
	
			String code = action.execut(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();
		}

增强

增强子控制器
下面我们要对子控制器进行一个增强
主控制器会对增幅版的子控制器进行一个调用
下面我们来看看这份增强版的子控制器

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

改写

改写什么呢?上一篇博客我们写的是计算器的算法,这下我们需要对计算器的算法进行一个改写
这样会简化很多不必要的类
CalAction
加减乘除

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("res", Integer.valueOf(cal.getNum1()) + Integer.valueOf(cal.getNum2()));
		return "calRes";
	}
	
	
	public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("res", Integer.valueOf(cal.getNum1()) - Integer.valueOf(cal.getNum2()));
		return "calRes";
	}

	public String multiply(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("res", Integer.valueOf(cal.getNum1()) * Integer.valueOf(cal.getNum2()));
		return "calRes";
	}
	

	public String divide(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("res", Integer.valueOf(cal.getNum1()) / Integer.valueOf(cal.getNum2()));
		return "calRes";
	}

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

配置

必不可少的web.xml的配置
yz_mvc的昵称

<?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" version="3.1">
  <display-name>yz_mvc</display-name>
  <servlet>
  	<servlet-name>disspatcherServlet</servlet-name>
  	<servlet-class>com.zking.framework.DisspatcherServlet</servlet-class>
  	
  		<init-param>
 		<param-name>xmlPath</param-name>
 		<param-value>/mvc.xml</param-value>
 	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>disspatcherServlet</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>

其次是config.xml的配置
这个是判断转发类型的配置器
false与true

<config>
	<!-- <action path="/addCal" type="com.zking.web.AddCalAction">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />
	</action>
	
	<action path="/delCal" type="com.zking.web.delCalAction2">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />
	</action>
	
	<action path="/chenCal" type="com.zking.web.chenCalAction2">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />
	</action>
	
	<action path="/chuCal" type="com.zking.web.chuCalAction3">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />
	</action> -->
	<action path="/cal" type="com.zking.web.CalAction">
		<forward name="calRes" path="/calRes.jsp" redirect="false" />  
	</action>
</config>

模型驱动接口

这个接口是用来干什么的呢?

原来 是用来处理jsp页面传递过来的参数,
将所有的参数自动封装到实体类T中


public interface ModelDrive<T> {
	
	T getModel();
}

UI界面

我们将src里的东西做完之后我们就需要改变jsp文件里面的内容了
以上一篇的博客的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(val){
		if(val==1){
			//calForm.action = "${pageContext.request.contextPath }/addCal.action";
			calForm.methodName.value = "add"
		}
		else if(val==2){
			//calForm.action = "${pageContext.request.contextPath }/delCal.action";
			calForm.methodName.value = "del"
		}
		else if(val==3){
			//calForm.action = "${pageContext.request.contextPath }/cCal.action";
			calForm.methodName.value = "c"
		}
		else if(val==4){
			//calForm.action = "${pageContext.request.contextPath }/xCal.action";
			calForm.methodName.value = "chu"
		}
		calForm.submit();
	}
</script>
</head>
<body>
	<form id="calForm" name="calForm" action="${pageContext.request.contextPath }/cal.action">
		num1:<input type="text" name="num1"><br>
		num2:<input type="text" name="num2"><br>
		<input type="hidden" name="methodName">
		<button onclick="doSub(1)">+</button>
		<button onclick="doSub(2)">-</button>
		<button onclick="doSub(3)">*</button>
		<button onclick="doSub(4)">/</button>
	</form>
</body>
</html>

如果有不了解的可以去看我上一篇的博客自定义简单mvc
今天的增强自定义mvc就是这样的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值