- 三次优化
三次优化
根据mvc01可知它的弊端:
package com.zhulinjun.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zhulinjun.framework.Action; public class orderAction extends Action{ public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("orderAction.add.."); } public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("orderAction.del.."); } public void upd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("orderAction.upd.."); } public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("orderAction.list.."); } }
package com.zhulinjun.framework; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; 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 com.zhulinjun.web.bookAction; import com.zhulinjun.web.orderAction; /** * 对应图中的ActionServlet:中央控制器 * @author 朱 */ @WebServlet("*.action") public class DispatcherServlet extends HttpServlet{ public Map<String, Action> actionMap=new HashMap<String, Action>(); @Override public void init(ServletConfig config) throws ServletException { actionMap.put("/order", new orderAction()); super.init(config); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //http://locahost:80/mvc/book.action?methodName=add String uri = req.getRequestURI(); uri= uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf(".")); Action action = actionMap.get(uri); action.excute(req, resp); } }
<%@ 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> <a href="order.action?methodName=add">增加</a> <a href="order.action?methodName=del">删除</a> <a href="order.action?methodName=upd">修改</a> <a href="order.action?methodName=list">查询</a> </body> </html>
1.第一次优化,版本5,将中央控制器中的action容器加载变成可配置
以前所有的子控制器是放到map集合中,现在所有的子控制器在mvc.xml中,其实就是放到configModel
常识:查询必然转发,增删改使用重定向
弊端:中央控制器中的action容器加载不可以灵活配置
package com.zhulinjun.model; 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 build(String xmlPath) throws Exception { ConfigModel configModel = new ConfigModel(); InputStream in = ConfigModelFactory.class.getResourceAsStream(xmlPath); SAXReader sr = new SAXReader(); Document doc = sr.read(in); // System.out.println(doc.asXML()); // configModel要有类容,就意味着actionmodel要有类容,然后放入到configmodel中去 List<Element> actionEles = doc.selectNodes("/config/action"); for (Element actionEle : actionEles) { // System.out.println(actionEle.asXML()); ActionModel actionModel = new ActionModel(); actionModel.setPath(actionEle.attributeValue("path")); actionModel.setType(actionEle.attributeValue("type")); // actionModel要有forwardModel,就意味着forwardmodel要有类容,然后放入到actionmodel中去 List<Element> forwardEles = actionEle.selectNodes("forward"); for (Element forwardEle : forwardEles) { System.out.println(forwardEle.asXML()); ForwardModel forwardModel = new ForwardModel(); forwardModel.setName(forwardEle.attributeValue("name")); forwardModel.setPath(forwardEle.attributeValue("path")); // 只有填写false才是转发,其它都为重定向 // forwardModel.setRedirect(false); forwardModel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect"))); actionModel.push(forwardModel); } configModel.push(actionModel); } return configModel; } public static ConfigModel build() throws Exception { return build("/mvc.xml"); } public static void main(String[] args) throws Exception { ConfigModelFactory.build(); } }
package com.zhulinjun.model; import java.util.HashMap; import java.util.Map; public class ActionModel { private String path; private String type; private Map<String, ForwardModel> fMap=new HashMap<String, ForwardModel>(); 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; } //将forward往action中放 压栈 public void push(ForwardModel forwardModel) { fMap.put(forwardModel.getName(), forwardModel); } // 从action中通过name值取出forward public ForwardModel pop(String name) { return fMap.get(name); } }
package com.zhulinjun.model; import java.util.HashMap; import java.util.Map; import org.dom4j.DocumentException; public class ConfigModel { private Map<String, ActionModel> aMap = new HashMap<String, ActionModel>(); public void push(ActionModel actionModel) { aMap.put(actionModel.getPath(), actionModel); } public ActionModel pop(String path) { return aMap.get(path); } public static void main(String[] args) throws Exception { ConfigModel configModel = new ConfigModelFactory().build(); ActionModel ActionModel = configModel.pop("/regAction"); ForwardModel forwardModel = ActionModel.pop("success"); System.out.println(forwardModel.getPath()); } }
package com.zhulinjun.framework; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; 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.dom4j.DocumentException; import com.zhulinjun.model.ActionModel; import com.zhulinjun.model.ConfigModel; import com.zhulinjun.model.ConfigModelFactory; import com.zhulinjun.model.ForwardModel; @WebServlet("*.action") public class DispatcherServlet extends HttpServlet { public Map<String, Action> actionMap = new HashMap<String, Action>(); // 以前所有的子控制器是放到map集合中,现在所有的子控制器在mvc.xml中,其实就是放到configModel private ConfigModel configModel; @Override public void init(ServletConfig config) throws ServletException { // actionMap.put("/book", new bookAction()); // actionMap.put("/order", new orderAction()); try { configModel=ConfigModelFactory.build(); } catch (Exception e) { e.printStackTrace(); } super.init(config); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // http://locahost:80/mvc/book.action?methodName=add String uri = request.getRequestURI(); // System.out.println(uri); uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".")); // System.out.println("url" + uri); // Action action = actionMap.get(uri); // 通过uri=/book,在configModel对象中找 ActionModel actionMondel = configModel.pop(uri); // System.out.println(actionMondel + "" + "actionMondel"); if (actionMondel == null) throw new RuntimeException("action not config"); // com.zking.web.BookAction String type = actionMondel.getType(); // BookAction bookaction=new BookAction(); action = (Action) Class.forName(type).newInstance(); action.execute(request, response); } }
package com.zhulinjun.framework; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 子控制器 * 正真做事,处理浏览器发送的请求的类 * @author 朱 * */ public class Action { protected String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName = request.getParameter("methodName"); String res=""; try { Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); // System.out.println("m"+m); m.setAccessible(true); res=(String) m.invoke(this, request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } }
2.第二次优化,针对于反射调用业务代码,最终页面跳转代码优化
<%@ 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> <p>版本5</p> <a href="book.action?methodName=add">增加</a> <a href="book.action?methodName=del">删除</a> <a href="book.action?methodName=upd">修改</a> <a href="book.action?methodName=list">查询</a> </body> </html>
package com.zhulinjun.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zhulinjun.framework.Action; public class bookAction extends Action{ public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.add..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.del..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String upd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.upd..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.list.."); request.setAttribute("content", "你好"); // request.getRequestDispatcher("res.jsp").forward(request, response); return "list"; } }
<%@ 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> 跳转成功:携带数据${content } </body> </html>
package com.zhulinjun.framework; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; 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.dom4j.DocumentException; import com.zhulinjun.model.ActionModel; import com.zhulinjun.model.ConfigModel; import com.zhulinjun.model.ConfigModelFactory; import com.zhulinjun.model.ForwardModel; @WebServlet("*.action") public class DispatcherServlet extends HttpServlet { public Map<String, Action> actionMap = new HashMap<String, Action>(); // 以前所有的子控制器是放到map集合中,现在所有的子控制器在mvc.xml中,其实就是放到configModel private ConfigModel configModel; @Override public void init(ServletConfig config) throws ServletException { // actionMap.put("/book", new bookAction()); // actionMap.put("/order", new orderAction()); try { configModel=ConfigModelFactory.build(); } catch (Exception e) { e.printStackTrace(); } super.init(config); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // http://locahost:80/mvc/book.action?methodName=add String uri = request.getRequestURI(); // System.out.println(uri); uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".")); // System.out.println("url" + uri); // Action action = actionMap.get(uri); // 通过uri=/book,在configModel对象中找 ActionModel actionMondel = configModel.pop(uri); // System.out.println(actionMondel + "" + "actionMondel"); if (actionMondel == null) throw new RuntimeException("action not config"); // com.zking.web.BookAction String type = actionMondel.getType(); // BookAction bookaction=new BookAction(); Action action; try { action = (Action) Class.forName(type).newInstance(); // 具体业务代码执行后的返回值 add/upd/del/list的返回值j==>list/tolist String res = action.execute(request, response); // 要通过返回值拿到,该方法结果是重定向还是转发,还是跳转哪个页面 ForwardModel forwardModel = actionMondel.pop(res); if(forwardModel!=null){ boolean redirect=forwardModel.isRedirect(); String path=forwardModel.getPath(); if(redirect) { response.sendRedirect(request.getContextPath() + "/" + path); }else { request.getRequestDispatcher(path).forward(request, response); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.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> </head> <body> <p>版本7</p> <a href="book.action?methodName=add&bid=1&bname=nb&price=9.9">增加</a> <a href="book.action?methodName=del">删除</a> <a href="book.action?methodName=upd">修改</a> <a href="book.action?methodName=list">查询</a> </body> </html>
package com.zhulinjun.web; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zhulinjun.entity.Book; import com.zhulinjun.framework.Action; import com.zhulinjun.model.MondelDriver; public class bookAction extends Action implements MondelDriver<Book>{ private Book book=new Book(); public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> parameterMap = request.getParameterMap(); /* * 1.要有表对应的属性对象Book book * 2.获取到所有的参数及参数req.getparamentMap(); * 3.将参数值封装到对应的对象中 * 4.要做到所有的子控制器通用 */ // String bid=request.getParameter("bid"); // String bname = request.getParameter("bname"); // String price=request.getParameter("price"); // Book book=new Book(); // book.setBid(Integer.valueOf(bid)); // book.setBname(bname); // book.setPrice(Float.valueOf(price)); // System.out.println("bookAction.add..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.del..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String upd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.upd..5"); request.setAttribute("content", "你好"); // response.sendRedirect("res.jsp"); return "toList"; } public String list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("bookAction.list.."); request.setAttribute("content", "你好"); // request.getRequestDispatcher("res.jsp").forward(request, response); return "list"; } @Override public Book getMondel() { // TODO Auto-generated method stub return book; } }
package com.zhulinjun.entity; public class Book { private int bid; private String bname; private float price; public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } public Book(int bid, String bname, float price) { super(); this.bid = bid; this.bname = bname; this.price = price; } public Book() { super(); // TODO Auto-generated constructor stub } }
package com.zhulinjun.model; /** * 模型驱动接口 * Book book=new Book(): * @author 朱 * * @param <T> */ public interface MondelDriver<T> { T getMondel(); }
package com.zhulinjun.framework; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; 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.dom4j.DocumentException; import com.zhulinjun.entity.Book; import com.zhulinjun.model.ActionModel; import com.zhulinjun.model.ConfigModel; import com.zhulinjun.model.ConfigModelFactory; import com.zhulinjun.model.ForwardModel; import com.zhulinjun.model.MondelDriver; @WebServlet("*.action") public class DispatcherServlet extends HttpServlet implements MondelDriver<Book>{ Book book=new Book(); public Map<String, Action> actionMap = new HashMap<String, Action>(); // 以前所有的子控制器是放到map集合中,现在所有的子控制器在mvc.xml中,其实就是放到configModel private ConfigModel configModel; @Override public void init(ServletConfig config) throws ServletException { // actionMap.put("/book", new bookAction()); // actionMap.put("/order", new orderAction()); try { configModel=ConfigModelFactory.build(); } catch (Exception e) { e.printStackTrace(); } super.init(config); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // http://locahost:80/mvc/book.action?methodName=add String uri = request.getRequestURI(); // System.out.println(uri); uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".")); // System.out.println("url" + uri); // Action action = actionMap.get(uri); // 通过uri=/book,在configModel对象中找 ActionModel actionMondel = configModel.pop(uri); // System.out.println(actionMondel + "" + "actionMondel"); if (actionMondel == null) throw new RuntimeException("action not config"); // com.zking.web.BookAction String type = actionMondel.getType(); // BookAction bookaction=new BookAction(); Action action; try { action = (Action) Class.forName(type).newInstance(); // bookaction有没有实现MondelDriver接口 if(action instanceof MondelDriver) { MondelDriver md=(MondelDriver) action; Object bean = md.getMondel(); Map<String, String[]> map = request.getParameterMap(); // 3.将参数值封装到对应的对象中 BeanUtils.populate(bean, request.getParameterMap()); } // 具体业务代码执行后的返回值 add/upd/del/list的返回值j==>list/tolist String res = action.execute(request, response); // 要通过返回值拿到,该方法结果是重定向还是转发,还是跳转哪个页面 ForwardModel forwardModel = actionMondel.pop(res); if(forwardModel!=null){ boolean redirect=forwardModel.isRedirect(); String path=forwardModel.getPath(); if(redirect) { response.sendRedirect(request.getContextPath() + "/" + path); }else { request.getRequestDispatcher(path).forward(request, response); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public Book getMondel() { // TODO Auto-generated method stub return book; } }