承接上文。StrutsContext类的实现。
初始化,创建ActionMap,扫描所有Action,将Action注册到filter里。
public StrutsContext(ServletContext servlet) {
actionList = new HashMap<>();
scanPaths(servlet, servlet.getResourcePaths(STR.SLASH_LEFT));
addMapping(servlet.getFilterRegistration("StrutsFilter"));
}
扫描所有Action,并解析后,加入到Action列表
private void scanPaths(ServletContext arg1, Set<String> paths) {
if (paths != null) {
for (String path : paths) {
if (path.endsWith(STR.SLASH_LEFT))
scanPaths(arg1, arg1.getResourcePaths(path));
else {
if (path.endsWith(STR.SUBFIX_CLASS)) {
Class<?> cla = getClass(path);
if (cla != null && !cla.isInterface()) {
if (isAction(cla))
bindAction(cla);
}
}
}
}
}
}
private void bindAction(Class<?> cla) {
String pkg = getMappingPath(cla);
Method[] methods = cla.getMethods();
String action;
for (Method method : methods) {
// 获取request路径
action = getMappingPath(pkg, method);
if (action != null) {
// 将有action链接的方法加入列表
actionList.put(action, new ActionMapper(method));
}
}
}
public static String getMappingPath(Class<?> cla) {
RequestMapping rm = cla.getAnnotation(RequestMapping.class);
if (rm != null)
return rm.value();
return "";
}
将Action添加到filter中,过滤所有配置的Action链接
private void addMapping(FilterRegistration filterRegistration) {
Set<String> actions = actionList.keySet();
EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
dispatcherTypes.add(DispatcherType.REQUEST);
dispatcherTypes.add(DispatcherType.FORWARD);
for (String action : actions) {
filterRegistration.addMappingForUrlPatterns(dispatcherTypes, true, action);
}
}
RequestMapping注解实现
@Retention(RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
public @interface RequestMapping {
String value() default "";
}
StrutsContext已经将所有的Action链接获取到了,下一步怎么办呢?
请看下一节。 一步一步写一个java web开发框架(4)