1, Mind map
2, Custom MVC
1. What is MVC?
MVC: ① Model layer is used to encapsulate; ② view layer is used to display ③ Control layer Used to accept browser requests for processing
2. Deficiency of previous Codes:
Data processing The code idea is basically repeated
2servlet The code idea is basically repeated
① doget/dopost. In fact, doget is basically useless
② Entity class parameters accept code redundancy (such as req. Getparameter (""), especially when there are many entity class attributes)
③ About page Jump (forwarding, redirection)
3. The idea of JSP code is basically repeated (HTML, js)
3. Solution:
① . general paging, addition, deletion and modification of single table (optimization)
② . servlet (and no redundant code) to customize mvc
③ . custom jsp Tags
4. Framework: Reflection + design pattern (it reduces the amount of code very little, and gives the repetitive code to the framework, so that programmers can focus on Project (business)
① . general paging guidance + general addition, deletion and modification
② Code reduction of data dao layer and control layer of each layer (MC)
③ . reduction and optimization of foreground code
3, Deductive process
1. In previous development, most developers would add, delete, modify and check in this way
Here you need to create addservlet, delservlet, updservlet, listservlet and bookservlet
(create as many servlets as you need)
increase package com.pjl.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book/add") public class AddServlet extends HttpServlet{ @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 { System.out.println("bookDao.add()..."); } } Delete package com.pjl.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book/del") public class DelServlet extends HttpServlet{ @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 { System.out.println("bookDao.del()..."); } } change package com.pjl.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book/upd") public class UpdServlet extends HttpServlet{ @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 { System.out.println("bookDao.upd()..."); } } check package com.pjl.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book/list") public class ListServlet extends HttpServlet { @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 { System.out.println("bookDao.list()..."); } }
JSP interface:
<%@ 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> <!-- Most people use this method to add, delete, modify and check( servlet Layer) --> <a href="${pageContext.request.contextPath }/book/add">newly added</a> <a href="${pageContext.request.contextPath }/book/del">delete</a> <a href="${pageContext.request.contextPath }/book/upd">modify</a> <a href="${pageContext.request.contextPath }/book/list">query</a> </body> </html>
The operation results are as follows:
2. A few developers use this method to add, delete, modify and query (Servlet layer)
package com.pjl.web; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book.action") @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 methodName = req.getParameter("methodName"); if("add".equals(methodName)) { add(req,resp); }else if("del".equals(methodName)) { del(req,resp); }else if("upd".equals(methodName)) { upd(req,resp); }else if("list".equals(methodName)) { list(req,resp); }else if("load".equals(methodName)) { load(req,resp); } } private void load(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.load2()"); } private void list(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.list2()"); } private void upd(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.upd2()"); } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.del2()"); } private void add(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.add2()"); } }
Advantages: the foreground sends a parameter to the background to call the corresponding method. Compared with the previous one, the amount of code is reduced, from the original four classes to one class
Disadvantages: each time a new method is added, the original logic must be changed to make the code too redundant
JSP page:
<%@ 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 few developers use this method to add, delete, modify and check( servlet Layer) --> <a href="${pageContext.request.contextPath }/book.action?methodName=add">Add 2</a> <a href="${pageContext.request.contextPath }/book.action?methodName=del">Delete 2</a> <a href="${pageContext.request.contextPath }/book.action?methodName=upd">Revision 2</a> <a href="${pageContext.request.contextPath }/book.action?methodName=list">Query 2</a> <a href="${pageContext.request.contextPath }/book.action?methodName=load">Echo 2</a> </body> </html>
The operation results are as follows:
3. Reflection optimization
advantage:
① Reflection can fix the defects above that change the code to solve the requirements problem
② Reflecting this code is equivalent to a central controller and does not directly control browser requests
It is the sub controller that handles the browser request
package com.pjl.web; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/book.action") public class BookServlet extends HttpServlet{ //The methodName method is called dynamically and is the methodName of the current class instance @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 methodName = req.getParameter("methodName"); try { Method m = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class); //Open access m.setAccessible(true); //Value transmission m.invoke(this,req,resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void load(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.load2()"); } private void list(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.list2()"); } private void upd(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.upd2()"); } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.del2()"); } private void add(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.add2()"); } private void ather(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.ather2()"); } }
3, Custom MVC framework
1. Optimization of central controller and sub controller
① . sub controller (Action interface) Processing browser requests
package com.pjl.framework; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Sub controller * Processing browser requests * Extract for add/del, abstract * @author zjjt * */ public interface Action { //This method is to extract by add/del, which is an abstract method //Function: it can handle "all" requests of the browser, including add/del //The return value determines which page to jump to (the redirection / forwarding is determined by the central controller) public String execute(HttpServletRequest req, HttpServletResponse resp); }
② . actionsupport (implement Action interface)
package com.pjl.framework; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Function: it can handle "all" requests of the browser, including add/del * * @author zjjt * */ public class ActionSupport implements Action { @Override public String execute(HttpServletRequest req, HttpServletResponse resp) { String methodName = req.getParameter("methodName"); String res=null; try { Method m = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class); //Open access m.setAccessible(true); //Value transmission res=(String) m.invoke(this,req,resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } }
③ . bookaction (inheriting ActionSupport)
package com.pjl.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pjl.entity.Book; import com.pjl.framework.ActionSupport; import com.pjl.framework.ModelDriver; public class BookAction extends ActionSupport implements ModelDriver<Book>{ public Book book=new Book(); @Override public Book getModel() { // TODO Auto-generated method stub return book; } //If you inherit the execute method from the parent class, you inherit the code that reflects the dynamic call method //BookAction is equivalent to the previous BookServlet //Where is the current sub controller called? Associate sub controls with browsers private String upd(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.upd3()"); return "upd"; } private String add(HttpServletRequest req, HttpServletResponse resp) { System.out.println(book); System.out.println("bookDao.add3(book)"); return "del"; } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.del3()"); } }
④ . central controller (DispatchServlet)
package com.pjl.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 com.pjl.web.BookAction; import com.pjl.web.GoodsAction; /** * The central controller * @author zjjt * jsp:/book.action * */ @WebServlet("*.action") public class DispatchServlet extends HttpServlet{ //There must be a set of all sub controllers in the current central controller private Map<String, ActionSupport> actions=new HashMap<String, ActionSupport>(); //Initialize all sub controllers to the current central controller public void init() throws ServletException { //There is a sub controller in the set //Defects: if there are additions, deletions, modifications and inspections of commodities, it is necessary to constantly accumulate them, which means that the code needs to be changed, and the code is not flexible enough try { actions.put("/book",new BookAction()); actions.put("/goods",new GoodsAction()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Associate the sub controller with the browser request and "find" the sub controller that can process the request //http://localhost:8080/book.action?methodName=add /**Idea: * 1.url-->book * 2.Find BookAction in actions through the book string * 3.Call the add of BookActions to delete the add. In fact, you just need to execute uniformly */ //Get the requested address of the browser String url = req.getRequestURI(); url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); ActionSupport action = actions.get(url); action.execute(req, resp); } }
⑤ The central controller (DispatchServlet) uses the jar package required for modeling and
Code display:
package com.pjl.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 com.pjl.web.BookAction; import com.pjl.web.GoodsAction; /** * The central controller * @author zjjt * jsp:/book.action * */ @WebServlet("*.action") public class DispatchServlet extends HttpServlet{ //There must be a set of all sub controllers in the current central controller //private Map<String, ActionSupport> actions=new HashMap<String, ActionSupport>(); private ConfigModel configModel=null; //Initialize all sub controllers to the current central controller @Override public void init() throws ServletException { //There is a sub controller in the set //Defects: if there are additions, deletions, modifications and inspections of commodities, it is necessary to constantly accumulate them, which means that the code needs to be changed, and the code is not flexible enough //Thinking: when bu changes the code, the central controller can also find the corresponding sub controller to process the browser's request //Scheme: add the logic / action of the sub controller into the configuration file to complete //The advantage of putting it in the configuration file is that the code is more flexible and don't touch the code when modifying information //The configModel object reads out all the configuration information through the modeling knowledge /* actions.put("/book",new BookAction()); actions.put("/goods",new GoodsAction());*/ try { configModel=ConfigModelFactory.build(); } catch (Exception e) { // TODO Auto-generated catch block 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 { // Associate the sub controller with the browser request and "find" the sub controller that can process the request //http://localhost:8080/book.action?methodName=add /**Idea: * 1.url-->book * 2.Find BookAction in actions through the book string * 3.Call the add of BookActions to delete the add. In fact, you just need to execute uniformly */ //Get the requested address of the browser String url = req.getRequestURI(); url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); //ActionSupport action = actions.get(url); //action.execute(req, resp); //Looking for the sub controller in the map is now looking for the sub controller in the configuration file /** * 1.Find the corresponding ActionModel object through / book * 2.Get the full pathname of the class com.zy.web.BookAction through the ActionModel object * 3.Reflect instanced objects * */ ActionModel actionModel = configModel.pop(url); //Get the full pathname String type = actionModel.getType(); ActionSupport action=null; try { action= (ActionSupport) Class.forName(type).newInstance(); action.execute(req, resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Test:
<%@ 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> <!-- Central controller and sub controller optimization --> <a href="${pageContext.request.contextPath }/book.action?methodName=add">Add 3</a> <a href="${pageContext.request.contextPath }/book.action?methodName=del">Delete 3</a> <a href="${pageContext.request.contextPath }/book.action?methodName=upd">Revision 3</a> </body> </html>
Operation results:
2. Entity class parameters accept code redundancy
① , book (entity class)
package com.pjl.entity; public class Book { public String bid; public String bname; public String price; public String athor; public String publish; public String getBid() { return bid; } public void setBid(String bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getAthor() { return athor; } public void setAthor(String athor) { this.athor = athor; } public String getPublish() { return publish; } public void setPublish(String publish) { this.publish = publish; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + ", athor=" + athor + ", publish=" + publish + "]"; } }
②,DispatchServlet
package com.pjl.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 org.dom4j.DocumentException; import com.pjl.servlet.BookAction; import com.pjl.servlet.GoodsAaction; /** * The central controller *jsp:/book.action/goods.action */ @WebServlet("*.action") public class DispatchServlet extends HttpServlet{ private ConfigModel configModel=null; @Override public void init() throws ServletException { try { configModel=ConfigModelFactory.build(); } 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 { //Get the requested address of the browser String uri = req.getRequestURI(); uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".")); ActionModel actionModel = configModel.pop(uri); String type = actionModel.getType(); ActionSupport action; try { action = (ActionSupport) Class.forName(type).newInstance(); //Complete entity parameter encapsulation //Execute business logic if(action instanceof ModelDriver) { //The current sub controller implements the model driven interface ModelDriver m=(ModelDriver) action; //Book/Goods/... Object bean = m.getModel(); //All request parameters are here. All request parameters need to be encapsulated in Book/Goods BeanUtils.populate(bean, req.getParameterMap()); //PropertyUtils.getProperty(bean, name); } action.execute(req, resp); } catch (Exception e) { e.printStackTrace(); } } }
③,ModelDriver<T>
package com.pjl.framework; /** * Model driven interface * Function: help the "central controller" complete the parameter packaging project * @author zjjt * */ public interface ModelDriver<T> { T getModel(); }
④, BookAction (extends ActionSupport implements ModelDriver<Book>)
package com.pjl.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pjl.entity.Book; import com.pjl.framework.ActionSupport; import com.pjl.framework.ModelDriver; public class BookAction extends ActionSupport implements ModelDriver<Book>{ public Book book=new Book(); @Override public Book getModel() { // TODO Auto-generated method stub return book; } //If you inherit the execute method from the parent class, you inherit the code that reflects the dynamic call method //BookAction is equivalent to the previous BookServlet //Where is the current sub controller called? Associate sub controls with browsers private void upd(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.upd3()"); } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.del3()"); } private void add(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.add3(book)"); } }
⑤ . test interface
<!--Duplicate parameters deal with the problem of code redundancy --> <form action="${pageContext.request.contextPath }/book.action?methodName=add" method="post"> book ID:<input type="text" name="bid" value="1"> Book name:<input type="text" name="bname" value="2"> Book price:<input type="text" name="price" value="24"> Book author:<input type="text" name="athor" value="5"> Book publishing house:<input type="text" name="publish" value="9"> <input type="submit"> </form>
3. Jump (forwarding, redirection) about the result page
①.Action
package com.pjl.framework; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Sub controller * Processing browser requests * Extract for add/del, abstract * @author zjjt * */ public interface Action { //This method is to extract by add/del, which is an abstract method //Function: it can handle "all" requests of the browser, including add/del //The return value determines which page to jump to (the redirection / forwarding is determined by the central controller) public String execute(HttpServletRequest req, HttpServletResponse resp); }
②.ActionSupport
package com.pjl.framework; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Function: it can handle "all" requests of the browser, including add/del * * @author zjjt * */ public class ActionSupport implements Action { @Override public String execute(HttpServletRequest req, HttpServletResponse resp) { String methodName = req.getParameter("methodName"); String res=null; try { Method m = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class); //Open access m.setAccessible(true); //Value transmission res=(String) m.invoke(this,req,resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } }
③BookAction
package com.pjl.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pjl.entity.Book; import com.pjl.framework.ActionSupport; import com.pjl.framework.ModelDriver; public class BookAction extends ActionSupport implements ModelDriver<Book>{ public Book book=new Book(); @Override public Book getModel() { // TODO Auto-generated method stub return book; } //If you inherit the execute method from the parent class, you inherit the code that reflects the dynamic call method //BookAction is equivalent to the previous BookServlet //Where is the current sub controller called? Associate sub controls with browsers private String upd(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.upd3()"); return "upd"; } private String add(HttpServletRequest req, HttpServletResponse resp) { System.out.println(book); System.out.println("bookDao.add3(book)"); return "del"; } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("bookDao.del3()"); } }
④DispatchServlet
package com.pjl.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 com.pjl.web.BookAction; import com.pjl.web.GoodsAction; /** * The central controller * @author zjjt * jsp:/book.action * */ @WebServlet("*.action") public class DispatchServlet extends HttpServlet{ //There must be a set of all sub controllers in the current central controller //private Map<String, ActionSupport> actions=new HashMap<String, ActionSupport>(); private ConfigModel configModel=null; //Initialize all sub controllers to the current central controller @Override public void init() throws ServletException { //There is a sub controller in the set //Defects: if there are additions, deletions, modifications and inspections of commodities, it is necessary to constantly accumulate them, which means that the code needs to be changed, and the code is not flexible enough //Thinking: when bu changes the code, the central controller can also find the corresponding sub controller to process the browser's request //Scheme: add the logic / action of the sub controller into the configuration file to complete //The advantage of putting it in the configuration file is that the code is more flexible and don't touch the code when modifying information //The configModel object reads out all the configuration information through the modeling knowledge /* actions.put("/book",new BookAction()); actions.put("/goods",new GoodsAction());*/ try { configModel=ConfigModelFactory.build(); } catch (Exception e) { // TODO Auto-generated catch block 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 { // Associate the sub controller with the browser request and "find" the sub controller that can process the request //http://localhost:8080/book.action?methodName=add /**Idea: * 1.url-->book * 2.Find BookAction in actions through the book string * 3.Call the add of BookActions to delete the add. In fact, you just need to execute uniformly */ //Get the requested address of the browser String url = req.getRequestURI(); url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); //ActionSupport action = actions.get(url); //action.execute(req, resp); //Looking for the sub controller in the map is now looking for the sub controller in the configuration file /** * 1.Find the corresponding ActionModel object through / book * 2.Get the full pathname of the class com.zy.web.BookAction through the ActionModel object * 3.Reflect instanced objects * */ ActionModel actionModel = configModel.pop(url); //Get the full pathname String type = actionModel.getType(); ActionSupport action=null; try { //Such as BookAction action= (ActionSupport) Class.forName(type).newInstance(); //Complete the encapsulation of entity class parameters if(action instanceof ModelDriver) { //The current sub controller implements the model driven interface ModelDriver m=(ModelDriver) action; //Book Object bean = m.getModel(); //All request parameters are here. You need to encapsulate all request parameters into Book/Goods/ BeanUtils.populate(bean, req.getParameterMap()); } //Execute the business logic. The return value of bookAction.add method is del /** * 1.If a book is added, it will jump to del.jsp for forwarding * 2.Book modification skip book.jsp redirection */ String res = action.execute(req, resp); //res is the return value ForwardModel forwardModel = actionModel.pop(res); String path = forwardModel.getPath(); boolean isredirect = forwardModel.isRedirect(); //It's redirection if(isredirect) { resp.sendRedirect(req.getContextPath()+path); }else { req.getRequestDispatcher(path).forward(req, resp); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
⑤config.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- config label:Can contain 0~N individual action label --> <config> <!-- action label:Can be full of 0~N individual forward label path:with/String beginning with,And the value must be unique and non empty type:character string,Non empty --> <!-- Each configuration added here is equivalent to writing actions.put("/goods",new GoodsAction());This solves the problem of code flexibility false Forwarding on behalf of--> <action path="/book" type="com.ysq.web.BookAction"> <forward name="del" path="/del.jsp" redirect="false" /> <forward name="upd" path="/book.jsp" redirect="true" /> </action> </config>
⑥ Testing
<%@ 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> <!--Duplicate parameters deal with the problem of code redundancy --> <form action="${pageContext.request.contextPath }/book.action?methodName=add" method="post"> <!-- --> <a href="${pageContext.request.contextPath }/book.action?methodName=add">Add 4</a> <a href="${pageContext.request.contextPath }/book.action?methodName=upd">Revision 4</a> </form> </body> </html>