一文了解自定義MVC框架實(shí)現(xiàn)
一、讓中央控制器動(dòng)態(tài)加載存儲(chǔ)子控制器
上期回顧,我們說(shuō)明了自定義MVC工作原理,其中,中央控制器起到了接收瀏覽器請(qǐng)求,找到對(duì)應(yīng)的處理人的一個(gè)作用,但是也存在缺陷,如:
就像在每一次顧客訪問(wèn)前臺(tái)時(shí),有很多個(gè)部門,比如說(shuō)料理部門,財(cái)務(wù)部門,每當(dāng)訪問(wèn)一次,就要new一個(gè)此類,代碼如下:
public void init() throws ServletException {
actions.put("/book", new BookAction());
actions.put("/order", new OrderAction());
}
解決方案:通過(guò)xml建模的知識(shí),到config文件中進(jìn)行操作。
目的:使代碼更加靈活
所以接下來(lái)對(duì)中央控制器進(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、通過(guò)url來(lái)找到config文件中對(duì)應(yīng)的action對(duì)象
2、然后通過(guò)該對(duì)象來(lái)取到路徑名servlet.BookAction
3、然后找到對(duì)應(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;
/**
* 中央控制器:
* 主要職能:接收瀏覽器請(qǐng)求,找到對(duì)應(yīng)的處理人
* @author 楊總
*
*/
@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
/**
* 通過(guò)建模我們可以知道,最終ConfigModel對(duì)象會(huì)包含config.xml中的所有子控制器信息
* 同時(shí)為了解決中央控制器能夠動(dòng)態(tài)加載保存子控制器的信息,那么我們只需要引入configModel對(duì)象即可
*/
private ConfigModel configModel;
// 程序啟動(dòng)時(shí),只會(huì)加載一次
@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,就是最后一個(gè)“/”到最后一個(gè)“.”為止
uri=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
// 相比于上一種從map集合獲取子控制器,當(dāng)前需要獲取config.xml中的全路徑名,然后反射實(shí)例化
ActionModel actionModel = configModel.pop(uri);
if(actionModel==null) {
throw new RuntimeException("action 配置錯(cuò)誤");
}
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、通過(guò)url來(lái)找到config文件中對(duì)應(yīng)的action對(duì)象
2、然后通過(guò)該對(duì)象來(lái)取到路徑名servlet.BookAction
3、然后找到對(duì)應(yīng)的方法執(zhí)行
展示效果:(當(dāng)自己點(diǎn)擊列表刪除時(shí),出現(xiàn)了“在同一個(gè)servlet中調(diào)用 del 方法”這效果,說(shuō)明用xml建模的知識(shí)去優(yōu)化中央控制器成功!)


但是注意,如果我們的路徑名不對(duì)的話,就會(huì)相應(yīng)的報(bào)錯(cuò)
比如:

原因:

所以:

二、參數(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ù)冗余問(wèn)題:
由于在做項(xiàng)目過(guò)程中,在servlet類中需要接受很多個(gè)參數(shù)值,所以就想到要解決當(dāng)前參數(shù)冗余問(wèn)題。比如:一個(gè)實(shí)體類Book當(dāng)中有二十個(gè)屬性,那么你在進(jìn)行修改時(shí)就要接受二十個(gè)值,雖然每次接受語(yǔ)句中的屬性值不一樣,但從根本上來(lái)講,性質(zhì)是一樣,要接收屬性。如下所示:(當(dāng)時(shí)此類沒有實(shí)現(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("在同一個(gè)servlet中調(diào)用 load 方法");
}
private void list(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)servlet中調(diào)用 list 方法");
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)servlet中調(diào)用 edit 方法");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)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("在同一個(gè)servlet中調(diào)用 add 方法");
}
}
解決方案:建一個(gè)模型驅(qū)動(dòng)接口,使BookAction實(shí)現(xiàn)該接口,在中央控制器中將所有要接收的參數(shù)封裝到模型接口中,從而達(dá)到簡(jiǎn)便的效果。
ModelDriven類(驅(qū)動(dòng)接口類):
package com.ycx.framework;
/**
* 模型驅(qū)動(dòng)接口,接收前臺(tái)JSP傳遞的參數(shù),并且封裝到實(shí)體類中
* @author 楊總
*
* @param <T>
*/
public interface ModelDriven<T> {
// 拿到將要封裝的類實(shí)例 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,就是最后一個(gè)“/”到最后一個(gè)“.”為止
uri=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
// Action action = actions.get(uri);
// 相比于上一種從map集合獲取子控制器,當(dāng)前需要獲取config.xml中的全路徑名,然后反射實(shí)例化
ActionModel actionModel = configModel.pop(uri);
if(actionModel==null) {
throw new RuntimeException("action 配置錯(cuò)誤");
}
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實(shí)例
Object model = md.getModel();
// 要給model中的屬性賦值,要接收前端jsp參數(shù) req.getParameterMap()
// PropertyUtils.getProperty(bean, name)
// 將前端所有的參數(shù)值封裝進(jìn)實(shí)體類
BeanUtils.populate(model, req.getParameterMap());
System.out.println(model);
}
// 正式調(diào)用方法前,book中的屬性要被賦值
action.execute(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}BookAction類:(注意,在上一張同一個(gè)類里,沒有實(shí)現(xiàn)ModelDriver接口,而如下bookaction類實(shí)現(xiàn)了ModelDriver接口,把接受多個(gè)參數(shù)的屬性值語(yǔ)句注釋,達(dá)到了簡(jiǎn)便的效果)
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("在同一個(gè)servlet中調(diào)用 load 方法");
}
private void list(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)servlet中調(diào)用 list 方法");
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)servlet中調(diào)用 edit 方法");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同一個(gè)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("在同一個(gè)servlet中調(diào)用 add 方法");
}
@Override
public Book getModel() {
return null;
}
}
Debug運(yùn)行效果如下:

其中關(guān)于解決參數(shù)冗余問(wèn)題關(guān)鍵代碼是:
BeanUtils.populate(bean, req.getParameterMap()); ???????//將該對(duì)象要接受的參數(shù)值封裝到對(duì)應(yīng)的對(duì)象中
三、對(duì)于方法執(zhí)行結(jié)果轉(zhuǎn)發(fā)重定向優(yōu)化
解決跳轉(zhuǎn)方式問(wèn)題:
在我們跳轉(zhuǎn)到另一個(gè)界面時(shí),需要許很多關(guān)于跳轉(zhuǎn)方式的代碼,有重定向,有轉(zhuǎn)發(fā),例如:
重定向:resp.sendRedirect(path);
轉(zhuǎn)發(fā): req.getRequestDispatcher(path).forward(req, resp);
這些代碼往往要寫很多次,因此通過(guò)配置config文件來(lái)解決此類問(wèn)題;
例如這一次我跳轉(zhuǎn)增加頁(yè)面時(shí)是轉(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)點(diǎn)擊增加或者編輯時(shí),首先跳轉(zhuǎn)的是中央控制器類(DispatchServlet):獲取到url,url將決定要跳到哪一個(gè)實(shí)體類,
2、之后進(jìn)入ActionSupport(子控制器接口實(shí)現(xiàn)類)通過(guò)methodname要調(diào)用什么方法,
3、再然后進(jìn)入到BookAction中調(diào)用methodname方法,找到對(duì)應(yīng)的返回值,
4、通過(guò)返回值在進(jìn)入到config文件找到path屬性,之后在中央控制器中進(jìn)行判斷,來(lái)決定是重定向還是轉(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(子控制器接口實(shí)現(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可能是多種方法
// 前臺(tái)傳遞什么方法就調(diào)用當(dāng)前類的對(duì)應(yīng)方法
try {
Method m=this.getClass()// BookServlet.Class
.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
// 調(diào)用當(dāng)前類實(shí)例的 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ā)頁(yè)面
</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)點(diǎn)擊增加時(shí),跳轉(zhuǎn)到demo2界面,顯示效果如下

2.當(dāng)點(diǎn)擊查詢時(shí),跳轉(zhuǎn)到demo3界面,顯示效果如下:

四、框架配置可變
如果config.xml文件名改成mvc.xml,該程序是否還可因運(yùn)行呢?答案肯定是不行的。

因?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框架實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)自定義MVC框架內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis-plus 攔截器敏感字段加解密的實(shí)現(xiàn)
數(shù)據(jù)庫(kù)在保存數(shù)據(jù)時(shí),對(duì)于某些敏感數(shù)據(jù)需要脫敏或者加密處理,本文主要介紹了mybatis-plus 攔截器敏感字段加解密的實(shí)現(xiàn),感興趣的可以了解一下2021-11-11
springboot+springJdbc+postgresql 實(shí)現(xiàn)多數(shù)據(jù)源的配置
本文主要介紹了springboot+springJdbc+postgresql 實(shí)現(xiàn)多數(shù)據(jù)源的配置,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Spring中@Service注解的作用與@Controller和@RestController之間區(qū)別
這篇文章主要介紹了Spring中@Service注解的作用與@Controller和@RestController之間的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-03-03
詳解Java中的延時(shí)隊(duì)列 DelayQueue
這篇文章主要介紹了Java中延時(shí)隊(duì)列 DelayQueue的相關(guān)資料,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12
java程序代碼與文本對(duì)比實(shí)用工具簡(jiǎn)介
可以對(duì)兩段文本進(jìn)行對(duì)比,檢測(cè)/比較兩個(gè)文本有什么不同的差異,以便修改,常用于程序代碼,就是不需要人工查看,尤其是大文件,有幾百上千行的代碼,這時(shí)候就建議使用比較工具了,不用浪費(fèi)過(guò)多時(shí)間去尋找2021-09-09
教你一步解決java.io.FileNotFoundException:找不到文件異常
這篇文章主要給大家介紹了關(guān)于如何一步解決java.io.FileNotFoundException:找不到文件異常的相關(guān)資料,文中通過(guò)圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01

