天天看点

MVC思路与错误解决总结未mvc增强mvc增强

mvc增强

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

任务:用mvc完成加减乘除

准备:

MVC思路与错误解决总结未mvc增强mvc增强

导4个jar包

MVC思路与错误解决总结未mvc增强mvc增强

案例

未mvc增强

准备:

  • DispatcherServlet中央控制器

    package wxm_mvc; 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; 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思路与错误解决总结未mvc增强mvc增强
    MVC思路与错误解决总结未mvc增强mvc增强

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; 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(); } }}

  • 核心代码
    MVC思路与错误解决总结未mvc增强mvc增强
    MVC思路与错误解决总结未mvc增强mvc增强
  • 前面的实体类不变
  • Add/Del/Mul/DiviCalAction 也不变
  • index.jsp 和rs.jsp也不变

    效果

    MVC思路与错误解决总结未mvc增强mvc增强

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

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

  • 中央控制器(DispatcherServlet )
    • DispatcherAction methodName:add/minus/mul/div CalAction extends DispatcherAction 提供一组与execute方法的参数、返回值相同的方法,只有方法名不一样
    • package wxm_mvc; 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(); } }}

    • 核心代码
    • MVC思路与错误解决总结未mvc增强mvc增强
    • 子控制器Action/mvc.xml/AddAction/del/mul/divi不变

      -CalAction中的转发和重定向注释

      例如

      MVC思路与错误解决总结未mvc增强mvc增强
      结果
      MVC思路与错误解决总结未mvc增强mvc增强

- 案例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; 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;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(); }

  • 效果
  • MVC思路与错误解决总结未mvc增强mvc增强

案例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 )
  • MVC思路与错误解决总结未mvc增强mvc增强
    • ModelDrivern
  • package com.wxm.framework;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;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(); }

  • 效果
    MVC思路与错误解决总结未mvc增强mvc增强
    这里注意理解
MVC思路与错误解决总结未mvc增强mvc增强

常见异常

MVC思路与错误解决总结未mvc增强mvc增强

如报null指针异常/你没有配置action标签,找不到对应的自控制器来处理浏览器发送出来的请求

解决方法 mvc.xml配置的的路径出了问题

如检查下面三个地方 是否正确

MVC思路与错误解决总结未mvc增强mvc增强
MVC思路与错误解决总结未mvc增强mvc增强
MVC思路与错误解决总结未mvc增强mvc增强

另一种情况会是

MVC思路与错误解决总结未mvc增强mvc增强

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

  • 在不改动framework文件里面的代码前提下,修改mvc.xml文件,

    新建一个与src同级下的wxm.xml)

    MVC思路与错误解决总结未mvc增强mvc增强
  • web.xml核心代码
<init-param>      <param-name>xmlPath</param-name>      <param-value>/wxm.xml</param-value></init-param>
           
MVC思路与错误解决总结未mvc增强mvc增强
  • 中央控制器核心代码
  • 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(); }

  • 效果
  • MVC思路与错误解决总结未mvc增强mvc增强
  • 名字要对应好, 这里我先示范举个错误的例子
    MVC思路与错误解决总结未mvc增强mvc增强