栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

J2EE基础-自定义MVC(中)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

J2EE基础-自定义MVC(中)

目录

前言

一、让中央控制器动态加载存储子控制器

二、 参数传递封装优化

三、 对于方法执行结果转发重定向优化

四、框架配置文本优化


前言

上次我们认识了自定义MVC原理(http://t.csdn.cn/S5TWs),今天了解的内容是自定义mvc框架实现(基于上篇文章进行优化)

一、让中央控制器动态加载存储子控制器

通过建模我们可以知道,最终configModel对象会包含config.xml中所有子控制器信息,同时为了解决中央控制器能够动态加载保存子控制器的信息,那么我们只需要引入configModel对象即可

 config.xml:



	
		
		
	

	
		
		
	

 优化DispatcherServlet: 

package com.oyang.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import com.oyang.servlet.BookAction;

//@WebServlet("*.action")
public  class DispatcherServlet extends HttpServlet{
	//private Map actions=new HashMap();
	
	
	private ConfigModel configModel;
	//程序启动时 ,只会加载一次
	@Override
	public void init() throws ServletException {
		//actions.put("/book",new BookAction());
		//actions.put("/order",new BookAction());
		try {
			//配置地址
			//getInitParameter的作用是拿到web.xml中的Servlet信息配置的参数
			String configLocation = this.getInitParameter("configLocation");
			if(configLocation==null || "".equals(configLocation))
				configModel=ConfigModelFactory.bulid();
			else
				configModel=ConfigModelFactory.bulid(configLocation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
		
	//只要是以.action结尾的每次请求都会被doPost截取
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		http://localhost:8080/mvc/book.action?methodName=list
		String uri = req.getRequestURI();
		// 要拿到/book,就是最后一个/到最后一个.为止
		uri= uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
		

		
		
		//Action action = actions.get(uri);
		//取到.action之后	Action action = actions.get(uri);里面定义了对应的方法
		//相比于上一种从map集合获取子控制器,当前需要获取config.xml中的全路径名,然后反射实例化
		ActionModel actionModel = configModel.pop(uri);
		if(actionModel==null) {
			throw new RuntimeException("action config eroer 配置错误");
		}
		String type = actionModel.getType();//拿到type值 
		//拿到type值之后就能通过路径名反射实例化 ------type是Action子控制器的全路径名
		try {
			Action action = (Action) Class.forName(type).newInstance();
			//此时的action 是bookAction
			if(action instanceof ModelDriven) {
				ModelDriven md=(ModelDriven) action;
				//action指的是bookAction,而bookAction又实现了ModelDriven接口,然后把bookAction转换成ModelDriven接口
				Object model = md.getModel();//model指的是bookAction中的book实例
				//给model中的属性赋值,要接收前端jsp传递过来的参数
				//PropertyUtils.getProperty(bean, name);//从某一个对象里面取某一个值
				//将前端所有参数值封装进实体类
				BeanUtils.populate(model, req.getParameterMap());
				System.out.println(model);
			} 
			//正式调用方法之前,book中的属性要被赋值
//			action.execute(req, resp);
			String retult = action.execute(req, resp);
			ForwardModel forwardModel = actionModel.pop(retult);
			if(forwardModel==null) {
				throw new RuntimeException("forward config error 配置错误");
			}
//			/bookList.jsp/index.jsp
			String path = forwardModel.getPath();
			//拿到是否需要转发的配置
			boolean redirect = forwardModel.getRedirect();
			if(redirect) 
				resp.sendRedirect(req.getServletContext().getContextPath()+path);
			else
			req.getRequestDispatcher(path).forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //Action的实例
	}
	//由原来的actions.get(uri)变成了从模型对象里取 
}	

 ConfigModel:

package com.oyang.framework;

import java.util.HashMap;
import java.util.Map;


public class ConfigModel {
	private Map aMap=new HashMap();
	
	public void push(ActionModel actionModel) {
		 aMap.put(actionModel.getPath(), actionModel);
	}
	
	public ActionModel pop(String path) {
		return aMap.get(path);
	}
	
}

ConfigModelFactory :

package com.oyang.framework;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class ConfigModelFactory {
	public static ConfigModel  bulid(String path) throws Exception {
		InputStream in = ConfigModelFactory.class.getResourceAsStream(path);
		SAXReader sr=new SAXReader();
		Document doc = sr.read(in);
		List actionEles = doc.selectNodes("/config/action");
		ConfigModel con=new ConfigModel();
		for (Element actionM : actionEles) {
			ActionModel actionModel = new ActionModel();
			actionModel.setPath(actionM.attributeValue("path"));
			actionModel.setType(actionM.attributeValue("type"));
			//将forwardmodel赋值并且添加到actionmodel中
			List forwardEles = actionM.selectNodes("forward");
			for (Element element : forwardEles) {
				ForwardModel forwardModel = new ForwardModel();
				forwardModel.setName(element.attributeValue("name"));
				forwardModel.setPath(element.attributeValue("path"));
//				redirect:只能是false|true,允许空,默认值为false
				forwardModel.setRedirect("true".equals(element.attributeValue("redirect")));
				actionModel.push(forwardModel);
			}
			con.push(actionModel);
		}
		return con;
	}
	
	
	public static ConfigModel  bulid() throws Exception {
		String defaultPath="/config.xml";
		return bulid(defaultPath);
	}
}

ForwardModel :

package com.oyang.framework;


public class ForwardModel {
	private String name;
	private String path;
	private boolean redirect;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public boolean getRedirect() {
		return redirect;
	}
	public void setRedirect(boolean b) {
		this.redirect = b;
	}
	
	
	
}

效果:

二、 参数传递封装优化

同常的Servlet:

private void add(HttpServletRequest request, HttpServletResponse response) {
	String bid = request.getParameter("bid");
	String bname = request.getParameter("bname");
	String price = request.getParameter("price");
	Book b=new Book(Integer.valueOf(bid), bname, Float.valueOf(price));
	//BookDao.add(b);
	System.out.println(book);
		//上述问题:如果一张表有20乃至50行数据,那岂不是要写那么多行去接收?如果有10张20条数据以上的表,那一个增加方法就得写很多行,甚至还有可能写错。大大的限制了我们的开发速度和效率
		//为了避免上述问题,如果上述代码可以不写就好了,那就不会这么麻烦了。能否让它们默认就接收那么多值呢?那我们就去生产这样的一个框架
		System.out.println("在同一个Servlet中调用add新增方法");
	}

上述问题:如果一张表有20乃至50行数据,那岂不是要写那么多行去接收?如果有10张20条数据以上的表,那一个增加方法就得写很多行,甚至还有可能写错。大大的限制了我们的开发速度和效率

解决方案:
为了避免上述问题,如果上述代码可以不写就好了,那就不会这么麻烦了。能否让它们默认就接收那么多值呢?那我们就去生产这样的一个框架

建立一个模型驱动接口,该接口目的是为了接受前台JSP传递的参数,并且封装到实体类中

ModelDriven :

package com.oyang.framework;


public interface ModelDriven {
	//拿到将要封装的类实例		ModelDriven.getModel()//当你要调用这个方法的时候等价于-->new Book();
	//此时new 的book是没有值的,我们去封装一下值
	T getModel();
}

此时new 的book是没有值的,我们去封装一下值

 BooKAction实现模型驱动接口:

package com.oyang.servlet;

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

import com.oyang.entity.Book;
import com.oyang.framework.Action;
import com.oyang.framework.ActionSupport;
import com.oyang.framework.ModelDriven;

public class BookAction extends ActionSupport implements ModelDriven{
	private  Book book=new Book();

	private void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用list查询方法");
	}
	
	private void load(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用load回显方法");
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用edit修改方法");
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用del删除方法");
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用add新增方法");
	}

	@Override
	public Book getModel() {
		return book;
	}

}

 将DispatcherServlet进行近一步的优化:

package com.oyang.framework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.oyang.servlet.BookAction;



//@WebServlet("*.action")
public  class DispatcherServlet extends HttpServlet{
	//private Map actions=new HashMap();
	
	
	private ConfigModel configModel;
	//程序启动时 ,只会加载一次
	@Override
	public void init() throws ServletException {
		//actions.put("/book",new BookAction());
		//actions.put("/order",new BookAction());
		try {
			//配置地址
			//getInitParameter的作用是拿到web.xml中的Servlet信息配置的参数
			String configLocation = this.getInitParameter("configLocation");
			if(configLocation==null || "".equals(configLocation))
				configModel=ConfigModelFactory.bulid();
			else
				configModel=ConfigModelFactory.bulid(configLocation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
		
	//只要是以.action结尾的每次请求都会被doPost截取
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		http://localhost:8080/mvc/book.action?methodName=list
		String uri = req.getRequestURI();
		// 要拿到/book,就是最后一个/到最后一个.为止
		uri= uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
		

		
		
		//Action action = actions.get(uri);
		//取到.action之后	Action action = actions.get(uri);里面定义了对应的方法
		//相比于上一种从map集合获取子控制器,当前需要获取config.xml中的全路径名,然后反射实例化
		ActionModel actionModel = configModel.pop(uri);
		if(actionModel==null) {
			throw new RuntimeException("action config eroer 配置错误");
		}
		String type = actionModel.getType();//拿到type值 
		//拿到type值之后就能通过路径名反射实例化 ------type是Action子控制器的全路径名
		try {
			Action action = (Action) Class.forName(type).newInstance();
			//此时的action 是bookAction
			if(action instanceof ModelDriven) {
				ModelDriven md=(ModelDriven) action;
				//action指的是bookAction,而bookAction又实现了ModelDriven接口,然后把bookAction转换成ModelDriven接口
				Object model = md.getModel();//model指的是bookAction中的book实例
				//给model中的属性赋值,要接收前端jsp传递过来的参数
				//PropertyUtils.getProperty(bean, name);//从某一个对象里面取某一个值
				//将前端所有参数值封装进实体类
				BeanUtils.populate(model, req.getParameterMap());
//				System.out.println(model);
			} 
			//正式调用方法之前,book中的属性要被赋值
//			action.execute(req, resp);
			String retult = action.execute(req, resp);
			ForwardModel forwardModel = actionModel.pop(retult);
			if(forwardModel==null) {
				throw new RuntimeException("forward config error 配置错误");
			}
//			/bookList.jsp/index.jsp
			String path = forwardModel.getPath();
			//拿到是否需要转发的配置
			boolean redirect = forwardModel.getRedirect();
			if(redirect) 
				resp.sendRedirect(req.getServletContext().getContextPath()+path);
			else
			req.getRequestDispatcher(path).forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //Action的实例
	}
	//由原来的actions.get(uri)变成了从模型对象里取 
}	

 效果:

我们可以看到原本Book没有值的当再一次点击的时候Book中又有值。 他大大减少了代码量,不管之后有多少属性,都可以接受属性值和封装

三、 对于方法执行结果转发重定向优化

对方法的执行结果进行优化,如果增加成功就用转发,失败就用重定向。 

编辑.xml配置文件:



	
		
		
	

	
		
		
	

对子控制器进行优化 Action :

package com.oyang.framework;

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


public interface Action {
	 String execute(HttpServletRequest request, HttpServletResponse response);
	 
}

 ActionSupport类:

package com.oyang.framework;

import java.lang.reflect.Method;

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

public class ActionSupport implements Action {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) {
		String methodName = request.getParameter("methodName");
		// methodName可能是add/del/edit/list/load/...
		// 前台传递什么方法,就调用当前类的对应方法
		try {
			Method m = this.getClass()// 当前类.class
					.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			// 打开权限
			m.setAccessible(true);
			// 调用当前类实例的methodName 方法
		return	(String) m.invoke(this, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

DispatcherServlet:

上述代码有,在此标记出来 

BookAction:(更改返回值)

package com.oyang.servlet;

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

import com.oyang.entity.Book;
import com.oyang.framework.Action;
import com.oyang.framework.ActionSupport;
import com.oyang.framework.ModelDriven;

public class BookAction extends ActionSupport implements ModelDriven{
	private  Book book=new Book();

	private String list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用list查询方法");
		return "success";
	}
	
	private void load(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用load回显方法");
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用edit修改方法");
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("在同一个Servlet中调用del删除方法");
	}

	private String add(HttpServletRequest request, HttpServletResponse response) {
//		String bid = request.getParameter("bid");
//		String bname = request.getParameter("bname");
//		String price = request.getParameter("price");
//		Book b=new Book(Integer.valueOf(bid), bname, Float.valueOf(price));
		//BookDao.add(b);
//		System.out.println(book);
		//上述问题:如果一张表有20乃至50行数据,那岂不是要写那么多行去接收?如果有10张20条数据以上的表,那一个增加方法就得写很多行,甚至还有可能写错。大大的限制了我们的开发速度和效率
		//为了避免上述问题,如果上述代码可以不写就好了,那就不会这么麻烦了。能否让它们默认就接收那么多值呢?那我们就去生产这样的一个框架
		System.out.println("在同一个Servlet中调用add新增方法");
		return "failed";
	}

	@Override
	public Book getModel() {
		return book;
	}
}

新建两个jsp界面,用于演示跳转转发&重定向

 

我们点击新增后的运行结果:

 

四、框架配置文本优化

以后我们使用的框架有很多,很有可能会重名,但是换了名字程序就跑不了了

对此问题我们只需要更改web.xml文件的配置就行了

 



  Oyang_mvc
  
  	mvc
  	com.oyang.framework.DispatcherServlet
	
		configLocation
		/oyang.xml
	
  
  
  
  	mvc
  	*.action
  

 试试运行结果:

点击增加

 跳转到转发界面

 

 看一下控制台打印的值

 敬请期待下篇J2EE基础-自定义MVC(下),下篇将会优化的更多


 OK,今日的学习就到此结束啦,如果对个位看官有帮助的话可以留下免费的赞哦(收藏或关注也行),如果文章中有什么问题或不足以及需要改正的地方可以私信博主,博主会做出改正的。个位看官,小陽在此跟大家说拜拜啦

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号