MVC思路与错误解决总结

本文详细介绍了通过XML配置实现MVC框架的增强,包括动态配置子控制器、简化页面跳转、将一组操作集中在一个Action中、利用ModelDriver接口对Java对象进行赋值,以及使框架配置文件可变等关键步骤。

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

mvc增强

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

任务:用mvc完成加减乘除

准备:
在这里插入图片描述
导4个jar包
在这里插入图片描述

案例

未mvc增强

准备:

  • DispatcherServlet中央控制器
    package wxm_mvc;/** * 中央控制器 * 作用: * 接受用户请求,通过用户请求的url寻找制定的子控制器去处理业务 * @author 2019071003 * */ 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.web.AddCalAction;import com.web.DelCalAction;import com.web.DiviCalAction;import com.web.MulCalAction;import com.wxm.framework.ActionModel;import com.wxm.framework.ConfigModel;import com.wxm.framework.ConfigModelFactory;import com.wxm.framework.ForwardModel;import com.wxm.framework.ModelDrivern; public class DispatcherServlet extends HttpServlet { private static final long serialVersionUID = 1971683367441467463L; private Map<String, Action> actionMap=new HashMap<>(); public void init() { //http://localhost:8080/wxm/cal_add.action actionMap.put("/cal_add", new AddCalAction()); actionMap.put("/cal_del", new DelCalAction()); actionMap.put("/cal_mul", new MulCalAction()); actionMap.put("/cal_divi", new DiviCalAction()); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub init(); String url=req.getRequestURI(); url=url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); Action action = actionMap.get(url); action.execute(req, resp);// }}
  • 子控制器Action
    package wxm_mvc; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; /** * 子控制器: * 作用:具体处理用户请求的类(实现了Action接口) * @author 2019071003 * */public interface Action { String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException;}
  • 创建四个实现请求的类
  • 加 AddCalAction
  • package com.web; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal; import wxm_mvc.Action; public class AddCalAction implements Action{ 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); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.parseInt(num2)); } // req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; };}
  • 减 DelCalAction
  • package com.web; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal; import wxm_mvc.Action; public class DelCalAction implements Action{ public String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { String num1=req.getParameter("num1"); String num2=req.getParameter("num2"); System.out.println(num1+num2); Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.parseInt(num2)); } // req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; };}
  • 乘 MulCalAction
  • package com.web; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal; import wxm_mvc.Action; public class MulCalAction implements Action{ public String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { String num1=req.getParameter("num1"); String num2=req.getParameter("num2"); System.out.println(num1+num2); Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.parseInt(num2)); } // req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; };}
  • package com.web; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal; import wxm_mvc.Action; public class DiviCalAction implements Action{ public String execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { String num1=req.getParameter("num1"); String num2=req.getParameter("num2"); System.out.println(num1+num2); Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.parseInt(num2)); } // req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; };}
  • 创建实体类(后面不会变)
  • Cal
  • package com.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;}public Cal(String num1, String num2) { super(); this.num1 = num1; this.num2 = num2;}public Cal() { super();}}
  • 配置安全目录web-inf下的web.xml(后面也不会变)
  • <?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>wxm_mvc</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>wxm_mvc.DispatcherServlet</servlet-class> <init-param> <param-name>xmlPath</param-name> <param-value>/mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping></web-app>
  • jsp展示页面index.jsp
  • <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!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=ISO-8859-1"><title>Insert title here</title><script type="text/javascript"> function doSub(v){if(v==1){ calForm.action="${pageContext.request.contextPath}/cal_add.action";}else if(v==2){ calForm.action="${pageContext.request.contextPath}/cal_del.action";}else if(v==3){ calForm.action="${pageContext.request.contextPath}/cal_mul.action";}else if(v==4){ calForm.action="${pageContext.request.contextPath}/cal_divi.action";}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>
  • rs.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></head><body>结果:${rs}</body></html>
  • mvc.xml(src目录下)
  • <?xml version="1.0" encoding="UTF-8"?><config><action path="/cal_add" type="com.web.AddCalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> </action> <action path="/cal_del" type="com.web.DelCalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> <action path="/cal_mul" type="com.web.DelCalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> <action path="/cal_divi" type="com.web.DelCalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> </action></config>
  • 运行到服务器后
  • 效果:
    在这里插入图片描述
    在这里插入图片描述

mvc增强

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

+ **解决了在框架代码中去改动,以便于完成客户需求,这个是不合理的

DispatcherServlet中央控制器: 作用:接受请求,通过请求寻找请求的对应的子控制器**
工具类:(直接用)

  • ActionModel:用来描述action标签
package com.wxm.framework; import java.io.Serializable;import java.util.HashMap;import java.util.Map; /** * 用来描述action标签 * @author Administrator * */public class ActionModel implements Serializable{ 	private static final long serialVersionUID = 6145949994701469663L;		private Map<String, ForwardModel> forwardModels = new HashMap<String, ForwardModel>();		private String path;		private String type;		public String getPath() {		return path;	} 	public void setPath(String path) {		this.path = path;	} 	public String getType() {		return type;	} 	public void setType(String type) {		this.type = type;	} 	public void put(ForwardModel forwardModel){		forwardModels.put(forwardModel.getName(), forwardModel);	}		public ForwardModel get(String name){		return forwardModels.get(name);	}	}
  • ConfigModel:用来描述config标签
package com.wxm.framework; import java.io.Serializable;import java.util.HashMap;import java.util.Map;  /** * 用来描述config标签 * @author Administrator * */public class ConfigModel implements Serializable{ 	private static final long serialVersionUID = -2334963138078250952L;		private Map<String, ActionModel> actionModels = new HashMap<String, ActionModel>();		public void put(ActionModel actionModel){		actionModels.put(actionModel.getPath(), actionModel);	}		public ActionModel get(String name){		return actionModels.get(name);	}}
  • ConfigModelFactory工厂模式创建config建模对象
package com.wxm.framework; import java.io.InputStream;import java.util.List; import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader; public class ConfigModelFactory {	private ConfigModelFactory() { 	} 	private static ConfigModel configModel = null; 	public static ConfigModel newInstance() throws Exception {		return newInstance("mvc.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();		}	}} 
  • ForwardModel用来描述forward标签
package com.wxm.framework; import java.io.Serializable; /** * 用来描述forward标签 * @author Administrator * */public class ForwardModel implements Serializable { 	private static final long serialVersionUID = -8587690587750366756L; 	private String name;	private String path;	private String 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 String getRedirect() {		return redirect;	} 	public void setRedirect(String redirect) {		this.redirect = redirect;	}
  • 中央控制器DispatcherServlet
  • package wxm_mvc;/** * 中央控制器 * 作用: * 接受用户请求,通过用户请求的url寻找制定的子控制器去处理业务 * * * 1,对存放子控制器action容器的增强 * ?原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的 * 处理方式:参照web.xml的实际方法,来完成中央的控制器管理子配置器的管理 * * * 2.处理结果码的跳转形式( req.getRequestDispatcher("/rs.jsp").forward(req, resp)/重定向;) * * 3.将一组操作放到一个子控制器去完成 * * * 4.处理jsp传递到后台的参数封装 * * 5.解决框架配置文件重名冲突问题 * @author 2019071003 * */ 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.web.AddCalAction;import com.web.DelCalAction;import com.web.DiviCalAction;import com.web.MulCalAction;import com.wxm.framework.ActionModel;import com.wxm.framework.ConfigModel;import com.wxm.framework.ConfigModelFactory;import com.wxm.framework.ForwardModel;import com.wxm.framework.ModelDrivern; public class DispatcherServlet extends HttpServlet{ private static final long serialVersionUID = 2304962805570259027L;// private Map<String, Action> actionMap=new HashMap<String, Action>(); private ConfigModel configModel=null; public void init() { //http://localhost:8080/wxm/cal_add.action// actionMap.put("/cal_add", new AddCalAction());// actionMap.put("/cal_del", new DelCalAction());// actionMap.put("/cal_mul", new MulCalAction());// actionMap.put("/cal_divi", new DiviCalAction()); //1.action的动态配置(建模) try { configModel=ConfigModelFactory.newInstance(); //替代了map } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub 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.get(url); try { Action action= (Action) Class.forName(actionModel.getType()).newInstance(); action.execute(req, resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
  • 核心代码
    在这里插入图片描述
    在这里插入图片描述
  • 前面的实体类不变
  • Add/Del/Mul/DiviCalAction 也不变
  • index.jsp 和rs.jsp也不变
    效果
    在这里插入图片描述

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

-就是简化( req.getRequestDispatcher("/rs.jsp").forward(req, resp)/重定向;)

  • 中央控制器(DispatcherServlet )

    • DispatcherAction methodName:add/minus/mul/div CalAction extends DispatcherAction 提供一组与execute方法的参数、返回值相同的方法,只有方法名不一样
    • package wxm_mvc;/** * 中央控制器 * 作用: * 接受用户请求,通过用户请求的url寻找制定的子控制器去处理业务 * * * 2.处理结果码的跳转形式( req.getRequestDispatcher("/rs.jsp").forward(req, resp)/重定向;)* @author 2019071003 * */ 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.web.AddCalAction;import com.web.DelCalAction;import com.web.DiviCalAction;import com.web.MulCalAction;import com.wxm.framework.ActionModel;import com.wxm.framework.ConfigModel;import com.wxm.framework.ConfigModelFactory;import com.wxm.framework.ForwardModel;import com.wxm.framework.ModelDrivern; public class DispatcherServlet extends HttpServlet{ private static final long serialVersionUID = 2304962805570259027L;// private Map<String, Action> actionMap=new HashMap<String, Action>(); private ConfigModel configModel=null; public void init() { //http://localhost:8080/wxm/cal_add.action// actionMap.put("/cal_add", new AddCalAction());// actionMap.put("/cal_del", new DelCalAction());// actionMap.put("/cal_mul", new MulCalAction());// actionMap.put("/cal_divi", new DiviCalAction()); //1.action的动态配置(建模) try { configModel=ConfigModelFactory.newInstance(); //替代了map } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub 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.get(url); try { Action action= (Action) Class.forName(actionModel.getType()).newInstance(); String code=action.execute(req, resp); ForwardModel forwardModel = actionModel.get(code); if(forwardModel!=null) { String jspPath = forwardModel.getPath(); if("false".equals(forwardModel.getRedirect())) {// 做转发的处理 req.getRequestDispatcher(jspPath).forward(req, resp); }else { resp.sendRedirect(req.getContextPath()+jspPath); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
    • 核心代码
    • 在这里插入图片描述
    • 子控制器Action/mvc.xml/AddAction/del/mul/divi不变
      -CalAction中的转发和重定向注释
      例如
      在这里插入图片描述
      结果
      在这里插入图片描述

- 案例3 将一组相关的操作放到一个Action中(反射调用方法)

  • DispatcherServlet 中央控制器
    核心代码
init();		String url=req.getRequestURI();		url=url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); 		ActionModel actionModel = configModel.get(url);		try {		 Action action =(Action) Class.forName(actionModel.getType()).newInstance();		 String code=action.execute(req, resp);		 ForwardModel forwardModel = actionModel.get(code);		 if(forwardModel!=null) {			 String jspPath = forwardModel.getPath();			 if("false".equals(forwardModel.getRedirect())) {//				 做转发的处理				 req.getRequestDispatcher(jspPath).forward(req, resp);				 			 }else {				 resp.sendRedirect(req.getContextPath()+jspPath);			 }		 }		 		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();				}
  • 子控制器(Action)----->增强版的子控制器(ActionSupport )
    package com.wxm.framework; import java.io.IOException;import java.lang.reflect.Method; import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import wxm_mvc.Action; /** * 增加版的子控制器 * 原来的子控制器只能处理有关用户请求 * 有时候,用户请求是多个,但是都是操作同一张表,那么原有的子控制器代码编写繁琐 * 增强版 将一组相关的操作放到一个Action中 * @author 2019071003 * */public class ActionSupport implements Action{ public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 传前台的什么方法,它(后台)就调用什么方法---动态方法调用(反射知识) String methodName=req.getParameter("methodName"); System.out.println(methodName); String code=null; //获取当前子控制器类的实例// this.在这里是指CalAction它的一个类实例 try { Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);//获取类对象 m.setAccessible(true);//设置权限 //动态调用add方法 //它也有返回值,是返回码 code=(String) m.invoke(this, req,resp); } catch (Exception e) { e.printStackTrace(); } return code; } }
  • mvc.xml
  • 核心代码
  • <action path="/cal" type="com.web.CalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> </action>
  • 加减乘除:
    package com.web; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal;import com.wxm.framework.ActionSupport;import com.wxm.framework.ModelDrivern;/**CalAction继承ActionSupport 实现ModeIDrivern<Cal> * 把(AddAction,DelAction,。。。)变成动态的 * @author 2019071003 * */public class CalAction extends ActionSupport implements ModelDrivern<Cal>{ private Cal cal=new Cal(); private String add(HttpServletRequest req,HttpServletResponse resp) { String num1=req.getParameter("num1"); String num2=req.getParameter("num2"); Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.parseInt(num2)); }req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String del(HttpServletRequest req,HttpServletResponse resp) {String num1=req.getParameter("num1"); String num2=req.getParameter("num2");Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.parseInt(num2));}req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String mul(HttpServletRequest req,HttpServletResponse resp) { String num1=req.getParameter("num1"); String num2=req.getParameter("num2"); Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.parseInt(num2)); } req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String divi(HttpServletRequest req,HttpServletResponse resp) { String num1=req.getParameter("num1"); String num2=req.getParameter("num2");Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.parseInt(num2)); } req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } public Cal getModel() { // TODO Auto-generated method stub return cal; } }
  • jsp页面:index.jsp
  • 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=mul"; }else if(v==4){ calForm.action="${pageContext.request.contextPath}/cal.action?methodName=divi"; } calForm.submit(); }
  • 效果
  • 在这里插入图片描述

案例4.利用ModelDriver接口对Java对象进行赋值(反射读写方法)

  • DispatcherServlet
  • 核心代码
try {		init();	String url=req.getRequestURI();	url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));	ActionModel actionModel=configModel.get(url);	if(actionModel==null) {		throw new RuntimeException("你没有配置action标签,找不到对应的自控制器来处理浏览器发送出来的请求 ");	}	//		Action action=(Action) Class.forName("com.web.AddCalAction").newInstance();//		Action action=(Action) AddCalAction();		//		action就是com.web.AddCalAction		Action action=(Action) Class.forName(actionModel.getType()).newInstance();		if(action instanceof ModelDrivern) {			ModelDrivern modelDrivern=(ModelDrivern) action;//			此时的model所有属性值是null			Object model = modelDrivern.getModel();//			给model赋值,那么意味着调用add/del的cal不再为空			BeanUtils.populate(model, req.getParameterMap());//			可以将req.getParameterMap()的值通过反射的方式将其塞进model实例			//		     原理//		     Map<String, String[]> paMap = req.getParameterMap();//		     Set<Entry<String, String[]>> entrySet = paMap.entrySet();//		     Class<? extends Object> cls = model.getClass();//		     for (Entry<String, String[]> entry : entrySet) {//		      Field field = cls.getDeclaredField(entry.getKey());//		      field.setAccessible(true);//		      field.set(model, entry.getValue());//		     }//	//		}		String code=action.execute(req, resp);				ForwardModel forwardModel=actionModel.get(code);		if(forwardModel!=null) {			String jspPath=forwardModel.getPath();			if("false".equals(forwardModel.getRedirect())) {//				做转发的处理				req.getRequestDispatcher(jspPath).forward(req, resp);			}else {//				注意:默认会缺失项目名				resp.sendRedirect(req.getContextPath()+jspPath);			} 		}		}	} catch (InstantiationException e) {		// TODO Auto-generated catch block		e.printStackTrace();	} catch (IllegalAccessException e) {		// TODO Auto-generated catch block		e.printStackTrace();	} catch (ClassNotFoundException e) {		// TODO Auto-generated catch block		e.printStackTrace();	} catch (InvocationTargetException e) {		// TODO Auto-generated catch block		e.printStackTrace();	}
  • ModelDriver接口对Java对象进行赋值(CalAction )

  • 在这里插入图片描述

    • ModelDrivern
  • package com.wxm.framework;/** * 模型驱动接口 * 作用 是将jsp所有传递过来的参数以及参数值都自动封装到浏览器所要操作的实体类中 * @author 2019071003 * * @param <T> */public interface ModelDrivern<T> { T getModel();}

  • 增删改查

  • package com.web; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.entity.Cal;import com.wxm.framework.ActionSupport;import com.wxm.framework.ModelDrivern;/**CalAction继承ActionSupport 实现ModeIDrivern<Cal> * 把(AddAction,DelAction,。。。)变成动态的 * @author 2019071003 * */public class CalAction extends ActionSupport implements ModelDrivern<Cal>{ private Cal cal=new Cal(); private String add(HttpServletRequest req,HttpServletResponse resp) {// String num1=req.getParameter("num1");// String num2=req.getParameter("num2");// Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.parseInt(cal.getNum2())); }// req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String del(HttpServletRequest req,HttpServletResponse resp) {// String num1=req.getParameter("num1");// String num2=req.getParameter("num2");// Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.parseInt(cal.getNum2())); }// req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String mul(HttpServletRequest req,HttpServletResponse resp) {// String num1=req.getParameter("num1");// String num2=req.getParameter("num2");// Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.parseInt(cal.getNum2())); }// req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } private String divi(HttpServletRequest req,HttpServletResponse resp) {// String num1=req.getParameter("num1");// String num2=req.getParameter("num2");// Cal cal=new Cal(num1, num2); if(cal.getNum1()!=null&&cal.getNum2()!=null) { req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.parseInt(cal.getNum2())); }// req.getRequestDispatcher("/rs.jsp").forward(req, resp); return "rs"; } public Cal getModel() { // TODO Auto-generated method stub return cal; } }

  • mvc.xml

  • <action path="/cal" type="com.web.CalAction"> <forward name="rs" path="/rs.jsp" redirect="false" /> </action>

  • index.jsp

  • 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=mul"; }else if(v==4){ calForm.action="${pageContext.request.contextPath}/cal.action?methodName=divi"; } calForm.submit(); }

  • 效果在这里插入图片描述这里注意理解

在这里插入图片描述

常见异常

在这里插入图片描述
如报null指针异常/你没有配置action标签,找不到对应的自控制器来处理浏览器发送出来的请求
解决方法 mvc.xml配置的的路径出了问题
如检查下面三个地方 是否正确
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
另一种情况会是
在这里插入图片描述

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

  • 在不改动framework文件里面的代码前提下,修改mvc.xml文件,
    新建一个与src同级下的wxm.xml)
    在这里插入图片描述
  • web.xml核心代码
 <init-param>      <param-name>xmlPath</param-name>      <param-value>/wxm.xml</param-value></init-param>

在这里插入图片描述

  • 中央控制器核心代码
  • try { String xmlPath=this.getInitParameter("xmlPath"); System.out.println(xmlPath); if(xmlPath==null||"".equals(xmlPath)) { configModel=ConfigModelFactory.newInstance(); }else { configModel=ConfigModelFactory.newInstance(xmlPath); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
  • 效果
  • 在这里插入图片描述
  • 名字要对应好, 这里我先示范举个错误的例子在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值