自定义MVC框架

Annotation

在JDK5之后,增加Annotation注解的基本语法,通 过注解可以省略XML的配置信息,简化代码的编写形 式。

在Annotation中,如果想要自定义,可以通过如下 语法:

@Target(ElementType.xxxx)

@Retention(RetentionPolicy.xxxx)

public @interface 注解名 {

}

Target:对应的是当前的注解能够定义在哪个位置 上

ElementType.Type -- 类

ElementType.Field --字段

ElementType.Method --方法

Retention:在什么场景下能够起作用。

RetentionPolicy.CLASS - 定义类

RetentionPolicy.SOURCE - 编写代码

RetentionPolicy.RUNTIME --运行时

1.定义两个annotation

@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.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}

@RequestMapping

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.解析Anonotation

2. 1 将所有包含了@Controller类进 行遍历

  • 扫描包的工具类                        

 ClassScanner

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) {
       initClassLoader();
    }

    private void initClassLoader() {
        //根据包找到报下面的所有类
        List<Class<?>> classList = ClassScanner.getClasssFromPackage("com.csi.controller");

        for (Class<?> clazz : classList) {
            //如果当前类上存在Controller,就要获取方法
            if (clazz.isAnnotationPresent(Controller.class)){
                Method[] methods = clazz.getMethods();

                //遍历当前包含了Controller注解的所有方法
                for (Method method : methods) {
                    //判断方法上是否添加了RequestMapping注解
                    if (method.isAnnotationPresent(RequestMapping.class)){
                        //获取到包含RequestMapping注解的value值
                        String urlPath = method.getAnnotation(RequestMapping.class).value();

                        //将值作为健,将方法作为值,存储在map集合中
                        WebApplicationContext.methodMap.put(urlPath,method);
                    }
                }

            }

        }
    }
}

 2.2 解析用户请求的路径

 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<>() ;

}

ClassLoaderContextListener 

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:获取到用户请求的url
        String urlPath = req.getServletPath();

        Method method = WebApplicationContext.methodMap.get(urlPath);
        if (method !=null){
            //步骤2:调用对应的Method方法
            Object instance = null;
            try {
                //2-1:如何找到对应的类
                instance = method.getDeclaringClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            //2-2:如何传输参数,req,resp
            try {
                method.invoke(instance,req,resp);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }else{
            resp.sendRedirect("failure.jsp");
        }
    }
}

3.使用

  • 需要在工程下建立com.csi.controller的包
  • 在包中建立类,在该类上,添加@Controller的 注解
  • 建立类中的方法,根据需求,在适当的方法上添 加@RequestMapping注解
  • 在@RequestMapping注解中添加url请求的路径

 ProductController

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("success");
            result.setCode(200);
            result.setData(products);
        }else{
            result.setCode(400);
            result.setMsg("数据为空!");
        }

        String jsonStr = JSON.toJSONString(result) ;

        PrintWriter out = response.getWriter() ;

        out.println(jsonStr);
    }


}

jsp页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<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>
<head>
    <title>Title</title>
</head>
<body>
<div id="data_show"></div>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值