目录
1.Annotation
- Target:对应的是当前的注解能够定义在哪个位置上
- ElementType.Type -- 类
- ElementType.Field --字段
-
ElementType.Method -- 方法
2. Retention:
在什么场景下能够起作用。
3.根据当前自定义MVC框架的一个需求,我们定义了两个Annotation:
package com.csi.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}
package com.csi.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value() default "";
}
2.解析Annotation
2.1将所有包含了@Controller 类进行遍历
-
扫描包的工具类
package com.csi.utils;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* 找到某个包下的所有的以.class结尾的java文件
*/
public class ClassScanner {
/**
* 获得包下面的所有的class
* @param
* @return List包含所有class的实例
*/
public static List<Class<?>> getClasssFromPackage(String packageName) {
List<Class<?>> clazzs = new ArrayList<>();
// 是否循环搜索子包
boolean recursive = true;
// 包名对应的路径名称 .转化为/
String packageDirName = packageName.replace('.', '/');
Enumeration<URL> dirs;
try {
//从当前正在运行的线程中,加载类加载器,通过给定的包名,找到所有该包下的类
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
findClassInPackageByFile(packageName, filePath, recursive, clazzs);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return clazzs;
}
/**
* 在package对应的路径下找到所有的class
*/
public static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive,
List<Class<?>> clazzs) {
File dir = new File(filePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 在给定的目录下找到所有的文件,并且进行条件过滤
File[] dirFiles = dir.listFiles(new FileFilter() {
public boolean accept(File file) {
boolean acceptDir = recursive && file.isDirectory();// 接受dir目录
boolean acceptClass = file.getName().endsWith("class");// 接受class文件
return acceptDir || acceptClass;
}
});
for (File file : dirFiles) {
if (file.isDirectory()) {
findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzs);
} else {
String className = file.getName().substring(0, file.getName().length() - 6);
try {
clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + "." + className));
} catch (Exception e) {
e.printstacktrace();
}
}
}
}
}
-
ClassLoaderContextListener
package com.csi.listener;
import com.csi.annotation.Controller;
import com.csi.annotation.RequestMapping;
import com.csi.utils.ClassScanner;
import javax.servlet.ServletContextEvent;
import javax.servlet.servletcontextlistener;
import java.lang.reflect.Method;
import java.util.List;
public class ClassLoaderContextListener implements servletcontextlistener {
@Override
public void contextinitialized(ServletContextEvent sce) {
//1.初始化
initClassLoader() ;
}
private void initClassLoader(){
//2.根据包找到包下面的所有类
List<Class<?>> classList = ClassScanner.getClasssFromPackage("com.csi.controller") ;
for (Class clazz : classList) {
//3.找到类上存在Controller,获取所有的方法
if (clazz.isAnnotationPresent(Controller.class)){
Method[] methods = clazz.getmethods();
//4.遍历当前包含了Controller 注解的方法
for (Method method : methods) {
//5.判断方法上有没有添加RequesrMapping 注解
if (method.isAnnotationPresent(RequestMapping.class)){
//6.获取到包含了 RequestMapping注解的value值
String urlPath = method.getAnnotation(RequestMapping.class).value();
WebApplicationContext.methodMap.put(urlPath,method) ;
}
}
}
}
}
}
2.2解析用户的路径
-
dispatcherServlet
package com.csi.servlet;
import com.csi.listener.WebApplicationContext;
import javax.servlet.servletexception;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class dispatcherServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws servletexception, IOException {
//1.获取访问的路径,然后得到对应下面的方法
String urlPath = req.getServletPath();
Method method = WebApplicationContext.methodMap.get(urlPath);
if (method != null) {
//2.method.getDeclaringClass()得到对应的字节码问价, newInstance()是实列话成为一个对象
//2.1调用对应的Method方法
Object instance = null;
try {
instance = method.getDeclaringClass().newInstance();
} catch (InstantiationException e) {
e.printstacktrace();
} catch (illegalaccessexception e) {
e.printstacktrace();
}
//2-2:如何传输参数,request,response invoke的第一个参数放置的是一个对象(object)
Object invoke = null;
try {
invoke = method.invoke(instance, req, resp);
} catch (illegalaccessexception e) {
e.printstacktrace();
} catch (InvocationTargetException e) {
e.printstacktrace();
}
} else {
resp.sendRedirect("failure.jsp");
}
}
}
-
WebApplicationContext
package com.csi.listener;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
public class WebApplicationContext {
public static ConcurrentHashMap<String, Method> methodMap = new ConcurrentHashMap<>() ;
}
- 下面是的自定义项目下的包和类
3.使用
- 需要在工程下建立com.csi.controller的包
- 在包中建立类,在该类上,添加@Controller的 注解
先看我工程shop里面的里面的部署
-
ProductController 控制层 和 index.jsp页面
package com.csi.controller;
import com.alibaba.fastjson.JSON;
import com.csi.annotation.Controller;
import com.csi.annotation.RequestMapping;
import com.csi.domain.Product;
import com.csi.domain.Result;
import com.csi.service.ProductService;
import com.csi.service.impl.ProductServiceImpl;
import javax.servlet.servletexception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@Controller
public class ProductController {
@RequestMapping("/product/toshowpage.do")
public void to_show_page(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException{
request.setAttribute("hello","world");
request.getRequestdispatcher("/show.jsp").forward(request,response);
}
@RequestMapping("/product/list.do")
public void list(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.setContentType("application/json;charset=utf-8");
int categoryId = Integer.parseInt(request.getParameter("categoryId"));
ProductService productService = new ProductServiceImpl() ;
List<Product> products = productService.listByCategory4Index(categoryId);
Result result =new Result() ;
if (products.size() !=0){
result.setMsg("成功了");
result.setCode(200);
result.setData(products);
}else {
result.setMsg("数据为空");
result.setCode(400);
}
PrintWriter out = response.getWriter();
String jsonStr = JSON.toJSONString(result);
out.println(jsonStr);
}
}
<%--
Created by IntelliJ IDEA.
User: W
Date: 2022/8/23
Time: 15:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="shortcut icon" href="#"/>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.get("/product/list.do?categoryId=548",function(data) {
if(data.code == 200) {
$(data.data).each(function(i,o) {
var divTag = "<div class='product_info'><img src='" + o.fileName + "'></img><p>" + o.name + "</p><p>¥" + o.price + "</p></div>" ;
$("#data_show").append(divTag) ;
}) ;
}else{
$("#data_show").html(data.msg) ;
}
}) ;
})
</script>
<style type="text/css">
.product_info{
border: 1px solid #c2e0d9;
float: left;
width: 200px;
}
</style>
</head>
<body>
<div id="data_show">
</div>
</body>
</html>