Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3593467
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Java

2022-08-19 14:27:13

public class DispatcherServlet extends HttpServlet {

    private Map mapping = new HashMap();

    @Override

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

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {

            doDispatch(req,resp);

        } catch (Exception e) {

            resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));

        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        String url = req.getRequestURI();

        String contextPath = req.getContextPath();

        url = url.replace(contextPath, "").replaceAll("/+", "/");

        if(!this.mapping.containsKey(url)){resp.getWriter().write("404 Not Found!!");return;}

        Method method = (Method) this.mapping.get(url);

        Map params = req.getParameterMap();

        method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]{req,resp,params.get("name")[0]});

    }

    //当我晕车的时候,我就不去看源码了

    //init方法肯定干得的初始化的工作

    //inti首先我得初始化所有的相关的类,IOC容器、servletBean

    @Override

    public void init(ServletConfig config) throws ServletException {

        InputStream is = null;

        try{

            Properties configContext = new Properties();

            is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));

            configContext.load(is);

            String scanPackage = configContext.getProperty("scanPackage");

            doScanner(scanPackage);

            for (String className : mapping.keySet()) {

                if(!className.contains(".")){continue;}

                Class clazz = Class.forName(className);

                if(clazz.isAnnotationPresent(Controller.class)){

                    mapping.put(className,clazz.newInstance());

                    String baseUrl = "";

                    if (clazz.isAnnotationPresent(RequestMapping.class)) {

                        RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);

                        baseUrl = requestMapping.value();

                    }

                    Method[] methods = clazz.getMethods();

                    for (Method method : methods) {

                        if (!method.isAnnotationPresent(RequestMapping.class)) {  continue; }

                        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

                        String url =跟单网gendan5.com (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");

                        mapping.put(url, method);

                        System.out.println("Mapped " + url + "," + method);

                    }

                }else if(clazz.isAnnotationPresent(Service.class)){

                        Service service = clazz.getAnnotation(Service.class);

                        String beanName = service.value();

                        if("".equals(beanName)){beanName = clazz.getName();}

                        Object instance = clazz.newInstance();

                        mapping.put(beanName,instance);

                        for (Class i : clazz.getInterfaces()) {

                            mapping.put(i.getName(),instance);

                        }

                }else {continue;}

            }

            for (Object object : mapping.values()) {

                if(object == null){continue;}

                Class clazz = object.getClass();

                if(clazz.isAnnotationPresent(Controller.class)){

                    Field [] fields = clazz.getDeclaredFields();

                    for (Field field : fields) {

                        if(!field.isAnnotationPresent(Autowired.class)){continue; }

                        Autowired autowired = field.getAnnotation(Autowired.class);

                        String beanName = autowired.value();

                        if("".equals(beanName)){beanName = field.getType().getName();}

                        field.setAccessible(true);

                        try {

field.set(mapping.get(clazz.getName()),mapping.get(beanName));

                        } catch (IllegalAccessException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

        } catch (Exception e) {

        }finally {

            if(is != null){

                try {is.close();} catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        System.out.print("MVC Framework is init");

    }

    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));

        File classDir = new File(url.getFile());

        for (File file : classDir.listFiles()) {

            if(file.isDirectory()){ doScanner(scanPackage + "." +  file.getName());}else {

                if(!file.getName().endsWith(".class")){continue;}

                String clazzName = (scanPackage + "." + file.getName().replace(".class",""));

                mapping.put(clazzName,null);

            }

        }

    }

}

阅读(471) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~