Java高薪训练营项目笔记,自定义mini版的MVC框架。通过自定义简单的mvc框架,你就知道ioc容器如何实现依赖注入的,url的请求如何分发,以及请求url如何找到对应的执行方法的基本流程:
(1)ioc容器的对象如何注入进来的;对象的属性实现依赖注入的,也就是如何将属性组装到对象中去的。
(2)请求的url如何找到controller和对应处理方法的。
(3)参数如何传递的到方法的。
(4)方法如何执行的。
本篇文章没有做视图解析器,也就是没有办法把请求返回的参数传递到页面上。但是可以清晰的实现,请求从浏览器到controller,到方法,再到service执行过程,最后返回到controller层。
1.自定义web.xml文件,配置分发器。这个LgDispatcherServlet就是我们自己定义的分发器servlet。其实就是对应的springframework的DispatcherServlet。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>lgoumvc</servlet-name>
<servlet-class>com.lagou.edu.mvcframework.servlet.LgDispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>springmvc.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>lgoumvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
2.重点,自定义LgDispatcherServlet类,这个类就是分发器,继承HttpServlet。这个类要做的事情很多。列举一下:
(1)加载配置文件 springmvc.properties
(2) 扫描相关的类,扫描注解
(3)初始化bean对象(实现ioc容器,基于注解)
(4)实现依赖注入
(5)构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系
(6)等待请求进来,就行调用处理
下面代码的init方法也是最终继承的servlet。这个就是启动项目初始化方法。
public class LgDispatcherServlet extends HttpServlet {
private static final String SLASH = "/";
private static final String BLANK = "";
private Properties properties = new Properties();
private List<String> classNames = new ArrayList<>(); // 缓存扫描到的类的全限定类名
// ioc容器
private Map<String,Object> ioc = new HashMap<String,Object>();
/**
* 存放uri和用户之间的映射关系,即该uri允许哪些用户访问
* key是url,List<String>是用户名
*/
private Map<String,List<String>> securityMap = new HashMap<>();
// handlerMapping
//private Map<String,Method> handlerMapping = now HashMap<>();
// 存储url和Method之间的映射关系
private List<Handler> handlerMapping = new ArrayList<>();
@Override
public void init(ServletConfig config) throws ServletException {
// 1 加载配置文件 springmvc.properties
String contextConfigLocation = config.getInitParameter("contextConfigLocation");
doLoadConfig(contextConfigLocation);
// 2 扫描相关的类,扫描注解
doScan(properties.getProperty("scanPackage"));
// 3 初始化bean对象(实现ioc容器,基于注解)
doInstance();
// 4 实现依赖注入
doAutoWired();
// 5 构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系
initHandlerMapping();
System.out.println("lagou mvc 初始化完成....");
// 等待请求进入,处理请求
}
//下面还有很多方法...一下逐一讲解。
}
3.自定义注解:@LagouAutowired,@LagouController,@LagouRequestMapping,@LagouSecurity,@LagouService。
4.加载配置文件。这个就是加载springmvc.properties配置文件。
5.扫描类,将类的全限定名加入到classNames中,也就是放到内存中,待用。
// 扫描类,将类的全限定名加入到classNames中,待用
private void doScan(String scanPackage) {
String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
+ scanPackage.replaceAll("\\.", "/");
File pack = new File(scanPackagePath);
File[] files = pack.listFiles();
for(File file: files) {
if(file.isDirectory()) {
//子package com.lagou.demo.controller
doScan(scanPackage + "." + file.getName());
}else if(file.getName().endsWith(".class")) {
String className = scanPackage + "." + file.getName().replaceAll(".class", "");
classNames.add(className);
}
}
}
6.初始化bean对象。原理和springbean的初始化原理一样,将含有注解@LagouController和
@LagouService注解类的对象包存到自定义的ioc容器中。我们这里的ioc容器就是一个hashMap对象,和Spring中的一样。
private void doInstance() {
if(classNames.size() == 0) return;
try{
for (int i = 0; i < classNames.size(); i++) {
// com.lagou.demo.controller.DemoController
String className = classNames.get(i);
// 反射
Class<?> aClass = Class.forName(className);
// 区分controller,区分service'
if(aClass.isAnnotationPresent(LagouController.class)) {
// controller的id此处不做过多处理,不取value了,就拿类的首字母小写作为id,保存到ioc中
String simpleName = aClass.getSimpleName();
String lowerFirstSimpleName = lowerFirst(simpleName);
Object o = aClass.newInstance();
ioc.put(lowerFirstSimpleName,o);
}else if(aClass.isAnnotationPresent(LagouService.class)) {
LagouService annotation = aClass.getAnnotation(LagouService.class);
//获取注解value值
String beanName = annotation.value();
// 如果指定了id,就以指定的为准
if(!"".equals(beanName.trim())) {
ioc.put(beanName,aClass.newInstance());
}else{
// 如果没有指定,就以类名首字母小写
beanName = lowerFirst(aClass.getSimpleName());
ioc.put(beanName,aClass.newInstance());
}
// service层往往是有接口的,面向接口开发,此时再以接口名为id,放入一份对象到ioc中,便于后期根据接口类型注入
Class<?>[] interfaces = aClass.getInterfaces();
for (int j = 0; j < interfaces.length; j++) {
Class<?> anInterface = interfaces[j];
// 以接口的全限定类名作为id放入
ioc.put(anInterface.getName(),aClass.newInstance());
}
}else{
continue;
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
7.实现依赖注入。其实就是把含有@LagouAutowired注解的属性的对象,组装到对应的Controller或者Service实例中。
private void doAutoWired() {
if(ioc.isEmpty()) {return;}
// 遍历ioc中所有对象,查看对象中的字段,是否有@LagouAutowired注解,如果有需要维护依赖注入关系
for(Map.Entry<String,Object> entry: ioc.entrySet()) {
// 获取bean对象中的字段信息
Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
// 遍历判断处理
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i]; // @LagouAutowired private IDemoService demoService;
if(!declaredField.isAnnotationPresent(LagouAutowired.class)) {
continue;
}
// 有该注解
LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
String beanName = annotation.value(); // 需要注入的bean的id
if("".equals(beanName.trim())) {
// 没有配置具体的bean id,那就需要根据当前字段类型注入(接口注入) IDemoService
beanName = declaredField.getType().getName();
}
// 开启赋值
declaredField.setAccessible(true);
try {
declaredField.set(entry.getValue(),ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
8.构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系,这点非常重要。请求怎么找到类,进而找到方法的,就是这里建立的映射关系。
private void initHandlerMapping() {
if(ioc.isEmpty()) {return;}
for(Map.Entry<String,Object> entry: ioc.entrySet()) {
// 获取ioc中当前遍历的对象的class类型
Class<?> aClass = entry.getValue().getClass();
if(!aClass.isAnnotationPresent(LagouController.class)) {continue;}
String baseUrl = "";
if(aClass.isAnnotationPresent(LagouRequestMapping.class)) {
LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
baseUrl = annotation.value(); // 等同于/demo
}
//handler类注解@LagouSecurity
initClassSecurityMap(baseUrl,aClass);
// 获取方法
Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// 方法没有标识LagouRequestMapping,就不处理
if(!method.isAnnotationPresent(LagouRequestMapping.class)) {continue;}
// 如果标识,就处理
LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
String methodUrl = annotation.value(); // /query
String url = baseUrl + methodUrl; // 计算出来的url /demo/query
// 把method所有信息及url封装为一个Handler
Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
// 计算方法的参数位置信息 // query(HttpServletRequest request, HttpServletResponse response,String name)
Parameter[] parameters = method.getParameters();
for (int j = 0; j < parameters.length; j++) {
Parameter parameter = parameters[j];
if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
// 如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse
handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
}else{
handler.getParamIndexMapping().put(parameter.getName(),j); // <name,2>
}
}
//方法注解@LagouSecurity
initMethodSecurityMap(url,method);
// 建立url和method之间的映射关系(map缓存起来)
handlerMapping.add(handler);
}
}
}
9.处理请求访问,servlet中有doGet和doPost方法,我们要实现该方法。我们这步要做的:
处理请求:根据url,找到对应的Method方法,进行反射执行方法invoke()调用。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Handler handler = getHandler(req);
if(handler == null) {
resp.getWriter().write("404 not found");
return;
}
logSecurityMap();
//判断权限
String url = req.getRequestURI();
String username = req.getParameter("username");
Boolean isHaveAuth = isUserNameHaveAuth(username,url);
if(!isHaveAuth){
resp.getWriter().write(username+",no auth...!");
return;
}
// 参数绑定
// 获取所有参数类型数组,这个数组的长度就是我们最后要传入的args数组的长度
Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
// 根据上述数组长度创建一个新的数组(参数数组,是要传入反射调用的)
Object[] paraValues = new Object[parameterTypes.length];
// 以下就是为了向参数数组中塞值,而且还得保证参数的顺序和方法中形参顺序一致
Map<String, String[]> parameterMap = req.getParameterMap();
// 遍历request中所有参数 (填充除了request,response之外的参数)
for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {
// name=1&name=2 name [1,2]
String value = StringUtils.join(param.getValue(), ","); // 如同 1,2
// 如果参数和方法中的参数匹配上了,填充数据
if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}
// 方法形参确实有该参数,找到它的索引位置,对应的把参数值放入paraValues
Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置
paraValues[index] = value; // 把前台传递过来的参数值填充到对应的位置去
}
int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
paraValues[requestIndex] = req;
int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
paraValues[responseIndex] = resp;
// 最终调用handler的method属性
try {
handler.getMethod().invoke(handler.getController(),paraValues);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
10.走到这一步,启动服务,ioc容器已经建立好了,url和handler方法之间的映射关系已经建立好了。等着请求进来。
11.此外,还有注解@LagouSecurity作为权限控制,给能够访问的用户加上权限。
12.请求访问:比如,http://localhost:8080/demo/handle01?username=zhangsan,
我们可以看到控制台打印情况:
如果大家想看详细的代码:https://gitee.com/sznsky/mvc。