当前位置:   article > 正文

手写精简版的springMVC框架_简化springmvc框架

简化springmvc框架

整个设计流程图

这里写图片描述

一、web.xml配置servlet(启动时运行级别的servlet)

<!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>
    <!-- 自定义spring mvc配置项目启动时加载 start -->
   <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>com.zzq.servlet.CustomDispatchrServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>application.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
   </servlet> 
   <!-- 自定义spring mvc配置项目启动时加载 end -->

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 实现几个必须的自定义注解
    CustomAutowired.java
package com.zzq.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomAutowired {
    String value() default "";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

CustomController.java

package com.zzq.annotation;

import java.lang.annotation.Documented;
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)
@Documented
public @interface CustomController {
    String value() default "";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

CustomRequestMapping.java

package com.zzq.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomRequestMapping {
    String value() default "";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

CustomRequestParam.java

package com.zzq.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomRequestParam {
    String value() default "";

    boolean required() default true;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

CustomService.java

package com.zzq.annotation;

import java.lang.annotation.Documented;
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)
@Documented
public @interface CustomService {
    String value() default "";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 再写service以及实现类
package com.zzq.core.service;

public interface DemoService {
    public void test();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
package com.zzq.core.service;

import com.zzq.annotation.CustomService;

@CustomService
public class DemoServiceImpl implements DemoService{

    @Override
    public void test() {
        // TODO Auto-generated method stub
        System.out.println("进入DemoServiceImpl test 方法");

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 这是controller
package com.zzq.core.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzq.annotation.CustomAutowired;
import com.zzq.annotation.CustomController;
import com.zzq.annotation.CustomRequestMapping;
import com.zzq.annotation.CustomRequestParam;
import com.zzq.core.service.DemoService;

/**
 * zhouzhongqing
 * 2017年11月29日22:11:56
 * 示例controller 
 * */
@CustomController
@CustomRequestMapping("/demo")
public class DemoController {

    @CustomAutowired
    private DemoService demoService;

    @CustomRequestMapping("/test.do") 
    public void test(HttpServletRequest request ,HttpServletResponse response ,@CustomRequestParam("password")String password) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response. setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
         /*
          * 如果没有配server.xml 的URIEncoding="UTF-8" 
          * <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1"  redirectPort="8443" URIEncoding="UTF-8" />
         出现乱码就可以用这个转为中文String resultName = new String(name.getBytes("ISO-8859-1"),"utf-8"); */
        String resultName = new String(name.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(demoService+"进入/demo/test方法--"+name +"----------"+resultName  +  " password : " + password);
        demoService.test();
        // response.getWriter().write(resultName); // 返回到页面字符串

        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

二、写一个自定义的CustomDispatchrServlet.java

  • 重写HttpServlet的init(ServletConfig config)方法, 读取配置文件application.properties,application.properties里配的是需要扫描的包的路径
scannerPackage=com.zzq.core
  • 1
private Properties pro = new Properties();

        //加载配置文件
        initLoadConfig(config.getInitParameter("contextConfigLocation"));
        //扫描类
        scanner(pro.getProperty("scannerPackage"));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
    private void initLoadConfig(String location) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/**
     * zhouzhongqing
     * 2017年12月8日21:23:55
     * 将全部的class添加到classs集合中
     * */
    private void scanner(String scannerPackage) {
        URL url = this.getClass().getClassLoader().getResource("/"+scannerPackage.replaceAll("\\.", "/"));
        File  dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if(file.isDirectory()){
                scanner(scannerPackage+"."+file.getName());
            }else{
                String calssName= scannerPackage + "." + file.getName().replace(".class", "");
                classs.add(calssName);
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 类初始化,并装载到ioc容器中
private Map<String,Object> ioc = new HashMap<>();
//类初始化,并装载到ioc容器中
instance();
  • 1
  • 2
  • 3

/**
* Controller注解和Service注解保存到ioc中建立对应关系
* */
private void instance() {
if(null == classs || classs.size() <= 0){
return;
}
try {
for (String className : classs) {

            Class<?> clazz = Class.forName(className);
            if(clazz.isAnnotationPresent(CustomController.class)){
                //保存到ioc中
                String beanName = lowerFirst(clazz.getSimpleName());
                ioc.put(beanName, clazz.newInstance());
            }else if(clazz.isAnnotationPresent(CustomService.class)){
                CustomService service = clazz.getAnnotation(CustomService.class);
                String beanName = service.value();
                if(null != beanName && !"".equals(beanName.trim())){
                    //如果是自定义了名称
                    ioc.put(beanName,clazz.newInstance());
                }else{
                    //如果没有定义名称就根据类名首字母小写命名
                    beanName = lowerFirst(clazz.getSimpleName());
                    ioc.put(beanName, clazz.newInstance());
                }
                //接口
                Class<?> [] interfaces = clazz.getInterfaces();
                for (Class<?> clz : interfaces) {
                    //clz.getName() : 接口的名称    clazz.newInstance() : 接口的实现类实例
                    ioc.put(clz.getName(), clazz.newInstance());
                }

            }
    }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 依赖注入,给加了Autowired注解的属性设置对应的值
//注入值
autowired();
  • 1
  • 2
/**
     * 给加了Autowired注解的属性设置对应的值
     * **/
    private void autowired() {

        if(null == ioc ||  ioc.size() <= 0){
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field [] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                //判断这个类的属性是否加了CustomAutowired注解
                if(!field.isAnnotationPresent(CustomAutowired.class)){
                    continue;
                }
                CustomAutowired autowired = field.getAnnotation(CustomAutowired.class);
                String beanName = autowired.value();
                if(null == beanName || "".equals(beanName.trim()) ){
                    //如果没有自定义命名 给加了CustomAutowired注解设置它类型名称默认值
                    beanName = field.getType().getName();
                }

                //即使是私有对象也要注入值
                field.setAccessible(true);
                try {
                    //利用反射给这个类 entry.getValue()的field属性设置这个值 ioc.get(beanName)
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    //e.printStackTrace();
                    System.err.println("注入异常--"+entry.getValue());
                }

            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 映射,将一个url映射到项目类的某个方法,建立url和method直接的关系
//映射,将一个url映射到项目类的某个方法
        initHandelMapping();
  • 1
  • 2
/**
     * 初始化加Controller注解的类,把地址和方法添加到handlerMapping映射中
     * **/
    private void initHandelMapping() {
        if(null == ioc ||  ioc.size() <= 0){
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            //判断是否加了CustomController注解
            if(!clazz.isAnnotationPresent(CustomController.class)){
                continue;
            }

            String  url = "";
            if(clazz.isAnnotationPresent(CustomRequestMapping.class)){
                CustomRequestMapping requestMapping = clazz.getAnnotation(CustomRequestMapping.class);
                url = requestMapping.value();

            }

            //得到这个类里面的所以方法
            Method [] methods = clazz.getMethods();
            for (Method method : methods) {
                //判断方法是否加了CustomRequestMapping注解
                if(!method.isAnnotationPresent(CustomRequestMapping.class)){
                    continue;
                }

                CustomRequestMapping requestMapping = method.getAnnotation(CustomRequestMapping.class);
                //String mUrl = ("/"+url+ requestMapping.value()).replaceAll("/+", "/");
                //handlerMapping.put(mUrl, method);
                //地址
                String regex = ("/"+url+ requestMapping.value()).replaceAll("/+", "/");
                //pattern() 返回正则表达式的字符串形式,其实就是返回Pattern.complile(String regex)的regex参数
                Pattern pattern = Pattern.compile(regex);
                //地址和方法建立对应关系
                handlerMapping.add(new Handler(pattern, entry.getValue(), method));
                System.out.println("mapping : "+ regex + "  method: " + method );


            }


        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

每一个步骤已经写完了。运行结果展示:

这里写图片描述

这里写图片描述

完整的CustomDispatchrServlet.java源码

package com.zzq.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzq.annotation.CustomAutowired;
import com.zzq.annotation.CustomController;
import com.zzq.annotation.CustomRequestMapping;
import com.zzq.annotation.CustomRequestParam;
import com.zzq.annotation.CustomService;

/***
 * zhouzhongqing
 * 2017年11月29日22:24:14
 * 自定义的DispatchrServlet
 * */
public class CustomDispatchrServlet extends HttpServlet {


    private Properties pro = new Properties();

    private List<String> classs = new LinkedList<>();

    private Map<String,Object> ioc = new HashMap<>();

//  private Map<String,Method> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new LinkedList<>();

    @Override  
    public void init(ServletConfig config) throws ServletException {
        System.out.println("/************************* dispatchrServlet  init start *************************/");

        //加载配置文件
        initLoadConfig(config.getInitParameter("contextConfigLocation"));
        //扫描类
        scanner(pro.getProperty("scannerPackage"));
        //类初始化,并装载到ioc容器中
        instance();

        //依赖注入
        autowired();

        //映射,将一个url映射到项目类的某个方法
        initHandelMapping();

        System.out.println("/************************* dispatchrServlet init end *************************/");
    }

    /**
     * 初始化加Controller注解的类,把地址和方法添加到handlerMapping映射中
     * **/
    private void initHandelMapping() {
        if(null == ioc ||  ioc.size() <= 0){
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            //判断是否加了CustomController注解
            if(!clazz.isAnnotationPresent(CustomController.class)){
                continue;
            }

            String  url = "";
            if(clazz.isAnnotationPresent(CustomRequestMapping.class)){
                CustomRequestMapping requestMapping = clazz.getAnnotation(CustomRequestMapping.class);
                url = requestMapping.value();

            }

            //得到这个类里面的所以方法
            Method [] methods = clazz.getMethods();
            for (Method method : methods) {
                //判断方法是否加了CustomRequestMapping注解
                if(!method.isAnnotationPresent(CustomRequestMapping.class)){
                    continue;
                }

                CustomRequestMapping requestMapping = method.getAnnotation(CustomRequestMapping.class);
                //String mUrl = ("/"+url+ requestMapping.value()).replaceAll("/+", "/");
                //handlerMapping.put(mUrl, method);
                //地址
                String regex = ("/"+url+ requestMapping.value()).replaceAll("/+", "/");
                //pattern() 返回正则表达式的字符串形式,其实就是返回Pattern.complile(String regex)的regex参数
                Pattern pattern = Pattern.compile(regex);
                //地址和方法建立对应关系
                handlerMapping.add(new Handler(pattern, entry.getValue(), method));
                System.out.println("mapping : "+ regex + "  method: " + method );


            }


        }
    }


    /**
     * 给加了Autowired注解的属性设置对应的值
     * **/
    private void autowired() {

        if(null == ioc ||  ioc.size() <= 0){
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field [] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                //判断这个类的属性是否加了CustomAutowired注解
                if(!field.isAnnotationPresent(CustomAutowired.class)){
                    continue;
                }
                CustomAutowired autowired = field.getAnnotation(CustomAutowired.class);
                String beanName = autowired.value();
                if(null == beanName || "".equals(beanName.trim()) ){
                    //如果没有自定义命名 给加了CustomAutowired注解设置它类型名称默认值
                    beanName = field.getType().getName();
                }

                //即使是私有对象也要注入值
                field.setAccessible(true);
                try {
                    //利用反射给这个类 entry.getValue()的field属性设置这个值 ioc.get(beanName)
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    //e.printStackTrace();
                    System.err.println("注入异常--"+entry.getValue());
                }

            }
        }
    }

    /**
     * Controller注解和Service注解保存到ioc中建立对应关系
     * */
    private void instance() {
        if(null == classs || classs.size() <= 0){
            return;
        }
        try {
        for (String className : classs) {

                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(CustomController.class)){
                    //保存到ioc中
                    String beanName = lowerFirst(clazz.getSimpleName());
                    ioc.put(beanName, clazz.newInstance());
                }else if(clazz.isAnnotationPresent(CustomService.class)){
                    CustomService service = clazz.getAnnotation(CustomService.class);
                    String beanName = service.value();
                    if(null != beanName && !"".equals(beanName.trim())){
                        //如果是自定义了名称
                        ioc.put(beanName,clazz.newInstance());
                    }else{
                        //如果没有定义名称就根据类名首字母小写命名
                        beanName = lowerFirst(clazz.getSimpleName());
                        ioc.put(beanName, clazz.newInstance());
                    }
                    //接口
                    Class<?> [] interfaces = clazz.getInterfaces();
                    for (Class<?> clz : interfaces) {
                        //clz.getName() : 接口的名称    clazz.newInstance() : 接口的实现类实例
                        ioc.put(clz.getName(), clazz.newInstance());
                    }

                }
        }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        String a = "";
        if(null != a && !"".equals(a.trim())){
            System.out.println(a);
            //自定义了名称
        }
    }


    /**
     * zhouzhongqing
     * 2017年12月8日21:23:55
     * 将全部的class添加到classs集合中
     * */
    private void scanner(String scannerPackage) {
        URL url = this.getClass().getClassLoader().getResource("/"+scannerPackage.replaceAll("\\.", "/"));
        File  dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if(file.isDirectory()){
                scanner(scannerPackage+"."+file.getName());
            }else{
                String calssName= scannerPackage + "." + file.getName().replace(".class", "");
                classs.add(calssName);
            }
        }
    }

    private void initLoadConfig(String location) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");
        dispatchr(req, resp);
        resp.getWriter().flush();
    }




    private void dispatchr(HttpServletRequest req, HttpServletResponse resp) {

        /*try {
            if(null == handlerMapping ||handlerMapping.size() <= 0){
                resp.getWriter().write("404 Not Found");    
            }
            boolean isPattern = false;
            String url =  req.getRequestURI();
            String contextPath = req.getContextPath();
            System.out.println(contextPath + "----"+url + handlerMapping);
            url = url.replace(contextPath, "").replaceAll("/+", "/");
            for (Entry<String, Method> mapping: handlerMapping.entrySet()) {
                System.out.println("mapping映射 "+mapping.getKey()+"------"+url );
                if(mapping.getKey().equals(url)){
                    System.out.println(mapping.getValue());
                    isPattern = true;
                    mapping.getValue();
                    break;
                }
            }

            if(!isPattern){
                System.err.println("404");
                resp.getWriter().write("404 Not Found");
            }

        } catch (Exception e) {
            try {
                resp.getWriter().write("404" + Arrays.toString(e.getStackTrace()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        */
        try {
            Handler handler = getHandler(req);
            if(null == handler){
                resp.getWriter().write("404 Not Found");
            }

            //得到全部的参数类型
            Class<?> [] paramTypes = handler.method.getParameterTypes();

            Object [] paramValues = new Object[paramTypes.length];

            //得到所有的请求参数
            Map<String, String[]> params = req.getParameterMap();
            for (Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                //判断传过来的参数名是否是加了CustomRequestParam自定义参数注解的
                if(!handler.paramIndexMapping.containsKey(param.getKey())){
                    continue;
                }
                //得到这个参数的位置
                int index = handler.paramIndexMapping.get(param.getKey());
                //转换成对应的参数类型 ,保存到paramValues数组中
                paramValues[index] = convert(paramTypes[index],value);

            }

            //获取方法参数中HttpServletRequest.class.getName()的位置
            int reqIndex = null == handler.paramIndexMapping.get(HttpServletRequest.class.getName()) ? -1 :  handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            if(-1 != reqIndex){
                paramValues[reqIndex] = req;
            }

            //获取方法参数中HttpServletResponse.class.getName()的位置
            int respIndex = null == handler.paramIndexMapping.get(HttpServletResponse.class.getName()) ? -1 : handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            if(-1 != respIndex){
                paramValues[respIndex] = resp;
            }
            //反射调用controller中的方法
            handler.method.invoke(handler.controller, paramValues);
        } catch (Exception e) {
            try {
                resp.getWriter().write(" error " +e);
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    private Object convert(Class<?> type, String value) {
        if( type == Integer.class){
            return Integer.valueOf(value);
        }
        return value;
    }

    private Handler getHandler(HttpServletRequest req) {

        if(handlerMapping.isEmpty()){
            return null;
        }
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.pattern.matcher(url);
            //判断是否有这个url
            if(!matcher.matches()){
                continue;
            }
            return handler;
        }

        return null;
    }

    private String lowerFirst(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }


    private class Handler{

        protected Object controller;//保存方法实例
        protected Method method; //保存映射方法
        protected Pattern pattern;
        protected Map<String,Integer> paramIndexMapping;//方法的参数

        protected Handler(Pattern pattern,Object controller,Method method){
            this.controller = controller;
            this.method = method;
            this.pattern = pattern;
            paramIndexMapping = new HashMap<>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {

            Annotation [] [] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length; i++) {
                for (Annotation a : pa[i]) {
                    //保存使用CustomRequestParam注解的参数
                    if(a instanceof CustomRequestParam){
                        String paramName = ((CustomRequestParam)a).value();
                        //System.out.println("paramName :" + paramName + " i : " +i );
                        if(null != paramName && !"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }

            }

            //保存HttpServletRequest和HttpServletResponse 参数
            Class<?> [] paramsTypes = method.getParameterTypes();
            for (int i = 0; i < pa.length; i++) {
                Class<?> type = paramsTypes[i];
                if(type == HttpServletRequest.class || type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }




    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418

源码下载地址:http://download.csdn.net/download/baidu_19473529/10268616

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/67755
推荐阅读
相关标签
  

闽ICP备14008679号