接续上一篇文章自定义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。
下一篇文章