自定义MVC的框架

目录

1.Annotation

2.解析Annotation

3.使用

1.Annotation


  • JDK5之后,增加Annotation注解的基本语法,通过注解可以省略XML的配置信息,简化代码的编写形
  • Annotation 中,如果想要自定义,可以通过如下语法

  1. Target:对应的是当前的注解能够定义在哪个位置上 
  •           ElementType.Type --
  •          ElementType.Field --字段  
  •         ElementType.Method -- 方法
    2. Retention: 在什么场景下能够起作用。
  •   RetentionPolicy.CLASS - 定义类
  •   RetentionPolicy.SOURCE - 编写代码
  •   RetentionPolicy.RUNTIME --运行时

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注解
  • 建立类中的方法,根据需求,在适当的方法上添加@RequestMapping注解
  • @RequestMapping注解中添加url请求的路径
先看我工程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>

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习编程?其实不难,不过在学习编程之前你得先了解你的目的是什么?这个很重要,因为目的决定你的发展方向、决定你的发展速度。
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面设计类、前端与移动、开发与测试、营销推广类、数据运营类、运营维护类、游戏相关类等,根据不同的分类下面有细分了不同的岗位。
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生学习Java开发,但要结合自身的情况,先了解自己适不适合去学习Java,不要盲目的选择不适合自己的Java培训班进行学习。只要肯下功夫钻研,多看、多想、多练
Can’t connect to local MySQL server through socket \'/var/lib/mysql/mysql.sock问题 1.进入mysql路径
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 sqlplus / as sysdba 2.普通用户登录
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服务器有时候会断掉,所以写个shell脚本每五分钟去判断是否连接,于是就有下面的shell脚本。
BETWEEN 操作符选取介于两个值之间的数据范围内的值。这些值可以是数值、文本或者日期。
假如你已经使用过苹果开发者中心上架app,你肯定知道在苹果开发者中心的web界面,无法直接提交ipa文件,而是需要使用第三方工具,将ipa文件上传到构建版本,开...
下面的 SQL 语句指定了两个别名,一个是 name 列的别名,一个是 country 列的别名。**提示:**如果列名称包含空格,要求使用双引号或方括号:
在使用H5混合开发的app打包后,需要将ipa文件上传到appstore进行发布,就需要去苹果开发者中心进行发布。​
+----+--------------+---------------------------+-------+---------+
数组的声明并不是声明一个个单独的变量,比如 number0、number1、...、number99,而是声明一个数组变量,比如 numbers,然后使用 nu...
第一步:到appuploader官网下载辅助工具和iCloud驱动,使用前面创建的AppID登录。
如需删除表中的列,请使用下面的语法(请注意,某些数据库系统不允许这种在数据库表中删除列的方式):
前不久在制作win11pe,制作了一版,1.26GB,太大了,不满意,想再裁剪下,发现这次dism mount正常,commit或discard巨慢,以前都很快...
赛门铁克各个版本概览:https://knowledge.broadcom.com/external/article?legacyId=tech163829
实测Python 3.6.6用pip 21.3.1,再高就报错了,Python 3.10.7用pip 22.3.1是可以的
Broadcom Corporation (博通公司,股票代号AVGO)是全球领先的有线和无线通信半导体公司。其产品实现向家庭、 办公室和移动环境以及在这些环境...
发现个问题,server2016上安装了c4d这些版本,低版本的正常显示窗格,但红色圈出的高版本c4d打开后不显示窗格,
TAT:https://cloud.tencent.com/document/product/1340