mvc(二)

一.什么是MVC

MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
核心思想:各司其职

二.MVC结构

V
jsp/ios/android
C
servlet/action
M
实体域模型(名词)
过程域模型(动词)
注1:不能跨层调用
注2:只能出现由上而下的调用

三.自定义MVC工作原理图

在这里插入图片描述

四.通过XML对自定义mvc框架进行增强

  1. 将Action的信息配置到xml(反射实例化)

  2. 通过结果码控制页面的跳转

  3. 将一组相关的操作放到一个Action中(反射调用方法)
    提供一组与execute方法的参数、返回值相同的方法,只有方法名不一样

  4. 利用ModelDriver接口对Java对象进行赋值(反射读写方法)
    ModelDriver接口返回的对象不能为空

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

进行增强操作时要建模,把之前写过的ActionModel,ConfigModel,ConfigModelFactory,ForwardModel导入项目中去或者另写都可以。还有要导入4个jar包
在这里插入图片描述
实体类Cal

package com.xfz.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;
	}
	@Override
	public String toString() {
		return "Cal [num1=" + num1 + ", num2=" + num2 + "]";
	}
	public Cal(String num1, String num2) {
		super();
		this.num1 = num1;
		this.num2 = num2;
	}
	public Cal() {
		super();
	}
	

}

需要一个中央控制器来接收用户请求,通过用户请求的url寻找指定的子控制器去处理业务

package com.xfz.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 org.apache.commons.beanutils.BeanUtils;

import com.xfz.web.AddCalAction;
import com.xfz.web.DelCalAction;

/**
 * @author ld
 * 中央控制器
 * 作用:
 * 接收用户请求,通过用户请求的url寻找指定的子控制器去处理业务
 * 
 * 1.对存放子控制器action容器的增强
 *  原因:原来为了完成业务需求,需要不断修改框架的代码  这样设计是不合理的
 *  处理方法:参照web.xml的设计方法,来完成中央控制器管理子控制器的动态配置
 * 
 * 2.处理结果码的跳转形式
 *  达到简化代码的目的
 *  
 * 3.将一组操作放到一个子控制器去完成
 * 
 * 4.处理jsp传递到后台的参数封装
 * 
 * 5.解决框架配置文件重名冲突问题
 */
public class DispatcherServlet extends HttpServlet{
	private static final long serialVersionUID = -7896263178241266783L;
//	private Map<String, Action> actionMap=new HashMap<String, Action>();
	private ConfigModel configModel=null;
	
	public void init() {
//		actionMap.put("/cal_add", new AddCalAction());
//		actionMap.put("/cal_del", new DelCalAction());
		try {
			String mvcXmlLocation=this.getInitParameter("mvcXmlLocation");
			if(null==mvcXmlLocation || "".equals(mvcXmlLocation)) {
				mvcXmlLocation="mvc.xml";
			}
			System.out.println("mvcXmlLocation:"+mvcXmlLocation);
			configModel=ConfigModelFactory.newInstance(mvcXmlLocation);
		} 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("."));
//		AddCalAction action=(AddCalAction) actionMap.get(url);
//		Action a=(Action)action;
//		Action action=actionMap.get(url);
//		action.execute(req, resp);
		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不再是空的
				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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

再需要一个控制器来具体处理用户请求的类

package com.xfz.framework;

import java.io.IOException;

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

/**
 * @author ld
 * 控制器
 * 作用:
 * 具体处理用户请求的类(实现了Action接口的类)
 */
public interface Action {
	String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException;

}

增强版的子控制器

package com.xfz.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 ld
 * 增强版的子控制器
 *  作用:将一组操作放到一个子控制器去完成
 */
public class ActionSupport implements Action{

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//从前台传递需要调用的方法名到后台,实现动态方法调用
		String methodName=req.getParameter("methodName");
		String code=null;
		try {
			Method m=this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			m.setAccessible(true);
			code=(String) m.invoke(this, req,resp);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return code;
	}

}

写一个模型驱动接口给对应处理业务的子控制器中包含的实体类进行jsp参数封装

package com.xfz.framework;

/**
 * @author ld
 * 模型驱动接口
 *  作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
 * @param <T>
 */
public interface ModelDriven<T> {
   T getModel();
}

将AddCalAction与DelCalAction(只是加减,乘除换个符号即可)合成为一个类CalAction
AddCalAction

package com.xfz.web;

import java.io.IOException;

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

import com.xfz.entity.Cal;
import com.xfz.framework.Action;

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";
	}

}

DelCalAction

package com.xfz.web;

import java.io.IOException;

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

import com.xfz.entity.Cal;
import com.xfz.framework.Action;

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 "rs";
	}

}

CalAction

package com.xfz.web;

import java.io.IOException;

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

import com.xfz.entity.Cal;
import com.xfz.framework.ActionSupport;
import com.xfz.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");
//		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";
	}
	
	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()));
//		req.getRequestDispatcher("/rs.jsp").forward(req, resp);
		return "rs";
	}
	
    //乘
	public String cheng(HttpServletRequest req,HttpServletResponse resp) {
	    req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
		return "rs";
	}
	
	//除
	public String chu(HttpServletRequest req,HttpServletResponse resp) {
	    req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
		return "rs";
	}

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

配置xml文件

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

最后写一个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(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" action="" 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个

红包金额最低5元

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

抵扣说明:

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

余额充值