一.Annotation注解
1.在JDK1.5之后,增加Annotation注解的基本语法,通过注解可以省略XML配置信息,简化代码的编写形式。
@Target(ElementType.Type)
@Retention(RetentionPolicy.RUNTIME)
public @interface Contrller{
}
2.解析Annotation解析
- 扫描包的工具类
- ClassLoadContextListener(在容器一打开,就把注解的类方法存入map集合)
public void contextInitialized(ServletContextEvent sce){
initClassLoader();
}
public void initClassLoader(){
List<Class<?>> classlist = ClassScanner.getClassFromPackage("com.csi.controller");
if(list.size()!=0){
for(Class clazz:classlist){
if(clazz.isAnnotationPresent(Controller.class)){
Method[] methods = clazz.getMethods();
for(Method method:methods){
if(method.isAnnotationPresent(method.class)){
String urlPath = method.getAnnotation(method.class).path();
ApplicationWebMap.methodMap.put(urlPath,method);
}
}
}
}
}
}
- Dispatcherservlet(生发,用户的请求都走这个类*.do)
protected void service(HttpServleRequest req,HttpServletResponse response){
String urlPath = req.getServletPath();
Method method = ApplicationWebMap.methodMap.get(urlPath);
if(method!=null){
Object instance = method.getDeclaringClass().newInstance();
method.invoke(instance,req,resp);
}else{
resp.sendRedirect("error.jsp");
}
}