一文了解自定義MVC框架實現(xiàn)
一、讓中央控制器動態(tài)加載存儲子控制器
上期回顧,我們說明了自定義MVC工作原理,其中,中央控制器起到了接收瀏覽器請求,找到對應(yīng)的處理人的一個作用,但是也存在缺陷,如:
就像在每一次顧客訪問前臺時,有很多個部門,比如說料理部門,財務(wù)部門,每當(dāng)訪問一次,就要new一個此類,代碼如下:
public void init() throws ServletException { actions.put("/book", new BookAction()); actions.put("/order", new OrderAction()); }
解決方案:通過xml建模的知識,到config文件中進(jìn)行操作。
目的:使代碼更加靈活
所以接下來對中央控制器進(jìn)一步作出優(yōu)化改進(jìn):
以前:
String url = req.getRequestURI(); //拿到book url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".")); ActionSupport action = actions.get(url); action.excute(req, resp);
現(xiàn)在改進(jìn)代碼:
1、通過url來找到config文件中對應(yīng)的action對象
2、然后通過該對象來取到路徑名servlet.BookAction
3、然后找到對應(yīng)的方法執(zhí)行
DispatcherServlet:
package com.ycx.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 com.ycx.web.BookAction; /** * 中央控制器: * 主要職能:接收瀏覽器請求,找到對應(yīng)的處理人 * @author 楊總 * */ @WebServlet("*.action") public class DispatcherServlet extends HttpServlet{ /** * 通過建模我們可以知道,最終ConfigModel對象會包含config.xml中的所有子控制器信息 * 同時為了解決中央控制器能夠動態(tài)加載保存子控制器的信息,那么我們只需要引入configModel對象即可 */ private ConfigModel configModel; // 程序啟動時,只會加載一次 @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 { //http:localhost:8080/mvc/book.action?methodName=list String uri=req.getRequestURI(); // 拿到/book,就是最后一個“/”到最后一個“.”為止 uri=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf(".")); // 相比于上一種從map集合獲取子控制器,當(dāng)前需要獲取config.xml中的全路徑名,然后反射實例化 ActionModel actionModel = configModel.pop(uri); if(actionModel==null) { throw new RuntimeException("action 配置錯誤"); } String type = actionModel.getType(); // type是Action子控制器的全路徑名 try { Action action= (Action) Class.forName(type).newInstance(); action.execute(req, resp); } catch (Exception e) { e.printStackTrace(); } } }
改進(jìn)思路:
1、通過url來找到config文件中對應(yīng)的action對象
2、然后通過該對象來取到路徑名servlet.BookAction
3、然后找到對應(yīng)的方法執(zhí)行
展示效果:(當(dāng)自己點擊列表刪除時,出現(xiàn)了“在同一個servlet中調(diào)用 del 方法”這效果,說明用xml建模的知識去優(yōu)化中央控制器成功!)
但是注意,如果我們的路徑名不對的話,就會相應(yīng)的報錯
比如:
原因:
所以:
二、參數(shù)傳遞封裝優(yōu)化
<h3>參數(shù)傳遞封裝優(yōu)化</h3> <a href="${pageContext.request.contextPath }/book.action?methodName=add & bid=989898 & bname=laoliu & price=89">增加</a> <a href="${pageContext.request.contextPath }/book.action?methodName=del">刪除</a> <a href="${pageContext.request.contextPath }/book.action?methodName=edit">修改</a> <a href="${pageContext.request.contextPath }/book.action?methodName=list">查詢</a> <a href="${pageContext.request.contextPath }/book.action?methodName=load">回顯</a>
解決參數(shù)冗余問題:
由于在做項目過程中,在servlet類中需要接受很多個參數(shù)值,所以就想到要解決當(dāng)前參數(shù)冗余問題。比如:一個實體類Book當(dāng)中有二十個屬性,那么你在進(jìn)行修改時就要接受二十個值,雖然每次接受語句中的屬性值不一樣,但從根本上來講,性質(zhì)是一樣,要接收屬性。如下所示:(當(dāng)時此類沒有實現(xiàn)Moderdriver接口)
package com.ycx.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ycx.entity.Book; import com.ycx.framework.Action; import com.ycx.framework.ActionSupport; import com.ycx.framework.ModelDriven; public class BookAction extends ActionSupport { private Book book=new Book(); private void load(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 load 方法"); } private void list(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 list 方法"); } private void edit(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 edit 方法"); } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 del 方法"); } private void add(HttpServletRequest req, HttpServletResponse resp) { String bid=req.getParameter("bid"); String bname=req.getParameter("bname"); String price=req.getParameter("price"); Book book=new Book(); book.setBid(Integer.valueOf(bid)); book.setBname(bname); book.setPrice(Float.valueOf(price)); bookDao.add(book); System.out.println("在同一個servlet中調(diào)用 add 方法"); } }
解決方案:建一個模型驅(qū)動接口,使BookAction實現(xiàn)該接口,在中央控制器中將所有要接收的參數(shù)封裝到模型接口中,從而達(dá)到簡便的效果。
ModelDriven類(驅(qū)動接口類):
package com.ycx.framework; /** * 模型驅(qū)動接口,接收前臺JSP傳遞的參數(shù),并且封裝到實體類中 * @author 楊總 * * @param <T> */ public interface ModelDriven<T> { // 拿到將要封裝的類實例 ModelDriven.getModel() ---> new Book(); T getModel(); }
DispatcherServlet 中央控制器類:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //http:localhost:8080/mvc/book.action?methodName=list String uri=req.getRequestURI(); // 拿到/book,就是最后一個“/”到最后一個“.”為止 uri=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf(".")); // Action action = actions.get(uri); // 相比于上一種從map集合獲取子控制器,當(dāng)前需要獲取config.xml中的全路徑名,然后反射實例化 ActionModel actionModel = configModel.pop(uri); if(actionModel==null) { throw new RuntimeException("action 配置錯誤"); } String type = actionModel.getType(); // type是Action子控制器的全路徑名 try { Action action= (Action) Class.forName(type).newInstance(); // action是bookAction if(action instanceof ModelDriven) { ModelDriven md=(ModelDriven) action; // model指的是bookAction中的book實例 Object model = md.getModel(); // 要給model中的屬性賦值,要接收前端jsp參數(shù) req.getParameterMap() // PropertyUtils.getProperty(bean, name) // 將前端所有的參數(shù)值封裝進(jìn)實體類 BeanUtils.populate(model, req.getParameterMap()); System.out.println(model); } // 正式調(diào)用方法前,book中的屬性要被賦值 action.execute(req, resp); } catch (Exception e) { e.printStackTrace(); } }
BookAction類:(注意,在上一張同一個類里,沒有實現(xiàn)ModelDriver接口,而如下bookaction類實現(xiàn)了ModelDriver接口,把接受多個參數(shù)的屬性值語句注釋,達(dá)到了簡便的效果)
package com.ycx.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ycx.entity.Book; import com.ycx.framework.Action; import com.ycx.framework.ActionSupport; import com.ycx.framework.ModelDriven; public class BookAction extends ActionSupport implements ModelDriven<Book>{ private Book book=new Book(); private void load(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 load 方法"); } private void list(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 list 方法"); } private void edit(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 edit 方法"); } private void del(HttpServletRequest req, HttpServletResponse resp) { System.out.println("在同一個servlet中調(diào)用 del 方法"); } private void add(HttpServletRequest req, HttpServletResponse resp) { // String bid=req.getParameter("bid"); // String bname=req.getParameter("bname"); // String price=req.getParameter("price"); Book book=new Book(); // book.setBid(Integer.valueOf(bid)); // book.setBname(bname); // book.setPrice(Float.valueOf(price)); // bookDao.add(book); System.out.println("在同一個servlet中調(diào)用 add 方法"); } @Override public Book getModel() { return null; } }
Debug運(yùn)行效果如下:
其中關(guān)于解決參數(shù)冗余問題關(guān)鍵代碼是:
BeanUtils.populate(bean, req.getParameterMap()); ???????//將該對象要接受的參數(shù)值封裝到對應(yīng)的對象中
三、對于方法執(zhí)行結(jié)果轉(zhuǎn)發(fā)重定向優(yōu)化
解決跳轉(zhuǎn)方式問題:
在我們跳轉(zhuǎn)到另一個界面時,需要許很多關(guān)于跳轉(zhuǎn)方式的代碼,有重定向,有轉(zhuǎn)發(fā),例如:
重定向:resp.sendRedirect(path);
轉(zhuǎn)發(fā): req.getRequestDispatcher(path).forward(req, resp);
這些代碼往往要寫很多次,因此通過配置config文件來解決此類問題;
例如這一次我跳轉(zhuǎn)增加頁面時是轉(zhuǎn)發(fā),跳轉(zhuǎn)查詢界面是重定向:
主界面代碼如下:
<a href="${pageContext.request.contextPath }/book.action?methodName=add & bid=989898 & bname=laoliu & price=89">增加</a> <a href="${pageContext.request.contextPath }/book.action?methodName=list">查詢</a>
config.xml :
<?xml version="1.0" encoding="UTF-8"?> <config> <action path="/book" type="com.ycx.web.BookAction"> <forward name="success" path="/demo2.jsp" redirect="false" /> <forward name="failed" path="/demo3.jsp" redirect="true" /> </action> </config>
思路:
1、當(dāng)點擊增加或者編輯時,首先跳轉(zhuǎn)的是中央控制器類(DispatchServlet):獲取到url,url將決定要跳到哪一個實體類,
2、之后進(jìn)入ActionSupport(子控制器接口實現(xiàn)類)通過methodname要調(diào)用什么方法,
3、再然后進(jìn)入到BookAction中調(diào)用methodname方法,找到對應(yīng)的返回值,
4、通過返回值在進(jìn)入到config文件找到path屬性,之后在中央控制器中進(jìn)行判斷,來決定是重定向還是轉(zhuǎn)發(fā)。
中央控制器(DispatcherServlet):
String result = action.execute(req, resp); ForwardModel forwardModel = actionModel.pop(result); // if(forwardModel==null) // throw new RuntimeException("forward config error"); String path = forwardModel.getPath(); // 拿到是否需要轉(zhuǎn)發(fā)的配置 boolean redirect = forwardModel.isRedirect(); if(redirect) //${pageContext.request.contextPath} resp.sendRedirect(req.getServletContext().getContextPath()+path); else req.getRequestDispatcher(path).forward(req, resp); } catch (Exception e) { e.printStackTrace(); } }
ActionSupport(子控制器接口實現(xiàn)類):
package com.ycx.framework; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ActionSupport implements Action{ @Override public String execute(HttpServletRequest req, HttpServletResponse resp) { String methodName = req.getParameter("methodName"); // methodName可能是多種方法 // 前臺傳遞什么方法就調(diào)用當(dāng)前類的對應(yīng)方法 try { Method m=this.getClass()// BookServlet.Class .getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); m.setAccessible(true); // 調(diào)用當(dāng)前類實例的 methodName 方法 return (String) m.invoke(this, req,resp); } catch (Exception e) { e.printStackTrace(); } return null; } }
BookAction(圖中標(biāo)記的為返回值):
config文件(圖中name為返回值,path為要跳轉(zhuǎn)的界面路徑名,redirect為跳轉(zhuǎn)方式):
demo2界面:
<%@ 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> 轉(zhuǎn)發(fā)頁面 </body> </html>
demo3界面:
<%@ 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> 重定向 </body> </html>
運(yùn)行結(jié)果:
1、當(dāng)點擊增加時,跳轉(zhuǎn)到demo2界面,顯示效果如下
2.當(dāng)點擊查詢時,跳轉(zhuǎn)到demo3界面,顯示效果如下:
四、框架配置可變
如果config.xml文件名改成mvc.xml,該程序是否還可因運(yùn)行呢?答案肯定是不行的。
因為 ConfigModelFactory 類里就定義了它的默認(rèn)路徑名如下:
我們可以在DispatcherServlet類里的init初始化里設(shè)置它的配置地址:
@Override public void init() throws ServletException { // actions.put("/book", new BookAction()); // actions.put("/order", new BookAction()); try { //配置地址 // getInitParameter的作用是拿到web.xml中的servlet信息配置的參數(shù) String configLocation = this.getInitParameter("configLocation"); if(configLocation==null||"".equals(configLocation)) configModel=ConfigModelFactory.build(); else configModel=ConfigModelFactory.build(configLocation); } catch (Exception e) { e.printStackTrace(); } }
web.xml :
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>T280_mvc</display-name> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>com.ycx.framework.DispatcherServlet</servlet-class> <init-param> <param-name>configLocation</param-name> <param-value>/yangzong.xml</param-value> </init-param> </servlet> <servlet-mapping> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
然后把config.xml改成yangzong.xml即可改變框架配置
到此這篇關(guān)于一文了解自定義MVC框架實現(xiàn)的文章就介紹到這了,更多相關(guān)自定義MVC框架內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis-plus 攔截器敏感字段加解密的實現(xiàn)
數(shù)據(jù)庫在保存數(shù)據(jù)時,對于某些敏感數(shù)據(jù)需要脫敏或者加密處理,本文主要介紹了mybatis-plus 攔截器敏感字段加解密的實現(xiàn),感興趣的可以了解一下2021-11-11springboot+springJdbc+postgresql 實現(xiàn)多數(shù)據(jù)源的配置
本文主要介紹了springboot+springJdbc+postgresql 實現(xiàn)多數(shù)據(jù)源的配置,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09Spring中@Service注解的作用與@Controller和@RestController之間區(qū)別
這篇文章主要介紹了Spring中@Service注解的作用與@Controller和@RestController之間的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03教你一步解決java.io.FileNotFoundException:找不到文件異常
這篇文章主要給大家介紹了關(guān)于如何一步解決java.io.FileNotFoundException:找不到文件異常的相關(guān)資料,文中通過圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01