自定義Java web框架(四)
阿新 • • 發佈:2018-12-18
接續上一篇文章自定義Java web框架(三) 本章主要講解如何處理Controller類,請求進入Controller類之後,根據請求的方法和路徑找到Controller類中的Action方法執行業務邏輯處理。 實現思路如下: 獲取所有定義了Controller註解的類,可以通過反射獲取該類的中所有帶有Action註解的方法,獲取Action註解中的請求表示式,進而獲取請求方法與請求路徑,封裝一個請求物件(Request)與處理物件(Handler),最後將Request與Handler建立一個對映關係,放入一個Action Map中,並提供一個可根據請求方法與請求路徑獲取處理物件的方法。
定義個Request類封裝請求資訊
public class Request { /** * 請求方法 */ private String requestMethod; /** * 請求路徑 */ private String requestPath; public Request(String requestMethod, String requestPath) { this.requestMethod = requestMethod; this.requestPath = requestPath; } public String getRequestMethod() { return requestMethod; } public String getRequestPath() { return requestPath; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } }
定義個Handler類,封裝Action資訊
public class Handler { /** * Controller類 */ private Class<?> controllerClass; /** * Action方法 */ private Method actionMethod; public Handler(Class<?> controllerClass, Method actionMethod) { this.controllerClass = controllerClass; this.actionMethod = actionMethod; } public Class<?> getControllerClass() { return controllerClass; } public Method getActionMethod() { return actionMethod; } }
定義個控制器助手類
public final class ControllerHelper {
/**
* 用於存放請求與處理器的對映關係(簡稱 Action Map)
*/
private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();
static {
//獲取所有Controller類
Set<Class<?>> controlllerClassSet = ClassHelper.getControllerClassSet();
if (CollectionUtil.isNotEmpty(controlllerClassSet)) {
//遍歷這些Controller類
for (Class<?> controllerClass : controlllerClassSet) {
//獲取Controller類中的方法
Method[] methods = controllerClass.getDeclaredMethods();
if (ArrayUtil.isNotEmpty(methods)) {
//遍歷類中的方法
for (Method method : methods) {
//判斷當前方法是否帶有Action註解
if (method.isAnnotationPresent(Action.class)) {
//從Action註解中獲取 URL 對映規則
Action action = method.getAnnotation(Action.class);
String mapping = action.value();
//驗證 URL 對映規則
if (mapping.matches("\\w+:/\\w*")) {
String[] array = mapping.split(":");
if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
//獲取請求方法與請求路徑
String requestMethod = array[0];
String requestPath = array[1];
Request request = new Request(requestMethod, requestPath);
Handler handler = new Handler(Controller.class, method);
//構建初始化Action Map
ACTION_MAP.put(request, handler);
}
}
}
}
}
}
}
}
/**
* 獲取Handler
* @param requestMethod
* @param requestPath
* @return
*/
public static Handler getHandler(String requestMethod, String requestPath) {
Request request = new Request(requestMethod, requestPath);
return ACTION_MAP.get(request);
}
}
程式碼地址如果本文對您有幫助, 動動小手給個star。