浅谈Spring-Mvc

Spring mvc

SpringMvc调用Controller的原理,
加载配置文件web.xml 加载spring mvc.xml
扫描整个项目 根据配置文件给定的目录来扫描,
扫描所有加了@Controller注解的类
当扫描到加@Controller注解的类之后遍历所有的方法,拿到方法对象之后,解析方法嗓门是否加了@RequestMapping注解,定义一个map集合把@RequestMapping的Value与方法对象绑定Map<String,Object>

拦截到对应的请求之后,拿到对象请求的URL,拿URL去map中get

模拟

继承一个httpServlet,重写doget、dopost、init

POM文件
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<!--dom4j 用来解析xml-->
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <finalName>spring-mvc</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <port>80</port>
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
</build>
Servlet.
package com.servlet;

import com.annotation.RequestMapping;
import com.annotation.ResponseBody;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 首先要有个servlet  拦截请求
 * 重写doGet doPost init
 */
public class SimulationDisoatcherServlet extends HttpServlet {

    //自己定义的接点
    private static String COMPENT_SCAN_ELEMENT_PACKAGE_NAME = "package";

    private static String COMPENT_SCAN_ELEMENT_NAME = "compentScan";

    //指定xml名字
    private static String XML_PATH_LOCAL = "xmlPathLocal";

    //项目路径
    private static String PROJECTPATH = SimulationDisoatcherServlet.class.getResource("/").getPath();

    private static Map<String, Method> methodMap = new HashMap<>();


    private  static String prefix = "";
    private  static String suffix = "";

    /**
     * 第一步解析web.xml 解析springMVC,xml
     * 第二部扫描整个项目
     *
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //第一步解析web.xml 解析springMVC,xml
        //整个是用户定义的xml地址 ---->Simulation.xml
        String Simulation = config.getInitParameter(XML_PATH_LOCAL);
        //解析xml文件
        //url转义
        try {
            PROJECTPATH = URLDecoder.decode(PROJECTPATH, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取java对象
        Document prase = prase(new File(PROJECTPATH));
        //获取对应的接点
        Element rootElement = prase.getRootElement();
        //拿到指定的接点
        Element compentScan = rootElement.element(COMPENT_SCAN_ELEMENT_NAME);
        //拿到对应的路径
        String stringValue = compentScan.element(COMPENT_SCAN_ELEMENT_PACKAGE_NAME).getStringValue();
        //第二部扫描整个项目

        super.init();
    }

    @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 {
        //拿到请求的URI
        String requestURI = req.getRequestURI();
        Method method = methodMap.get(requestURI);
        if (method!=null){
            //jdk8以前 直接拿参数名称 拿不到
            Parameter[] parameters = method.getParameters();
            Object[] objects = new Object[parameters.length];
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                String name = parameter.getName();
                Class type = parameter.getType();
                //参数类型
                if (type.equals(String.class)){
                    objects[i] = req.getParameter(name);
                }else if(type.equals(HttpServletRequest.class)){
                    objects[i] = req;
                }else if(type.equals(HttpServletResponse.class)){
                    objects[i] = resp;
                }else{
                //如果是对象
                    try {
                        Object o = type.newInstance();
	                    // type.getDeclaredConstructor().newInstance()
                        for (Field field : type.getDeclaredFields()) {
                            //如果有嵌套判断下类型 若还有递归取
                            field.setAccessible(true);
                            String fieldName = field.getName();
                            field.set(o,req.getParameter(fieldName));
                        }
                        objects[i] = o;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            try {
                Object o= null;
                o = method.getDeclaringClass().newInstance();
                Object invoke = method.invoke(o, objects);
                // 判断返回值是否是Void
                if (!method.getReturnType().equals(Void.class)){
                    ResponseBody annotation = method.getAnnotation(ResponseBody.class);
                    if (annotation!=null){
                        //提供接口来做这个事情
                        resp.getWriter().write(String.valueOf(invoke));
                    }else {
                        // /page/index.html   page/index.html
                        req.getRequestDispatcher(prefix+String.valueOf(invoke)+suffix).forward(req,resp);
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            resp.setStatus(404);
        }
    }


    /**
     * 解析xml
     *
     * @param file :你的xml文件对象
     * @return
     */
    public Document prase(File file) {
        SAXReader saxReader = new SAXReader();
        try {
            return saxReader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 递归解析项目所有文件
     *
     * @param path
     */
    public void scanProjectByPath(String path) {
        File file = new File(path);
        scanFile(file);
    }

    /**
     * 递归解析项目
     *
     * @param file
     */
    public void scanFile(File file) {
        //如果是文件
        if (file.isDirectory()) {
            for (File file1 : file.listFiles()) {
                scanFile(file1);
            }
        } else {
            //如果不是文件夹
            //E:\cloud\boot-demo\spring-mvc\src\main\java\com\controller\TestController.class
            //com.controller.TestController
            String filePath = file.getPath();
            //截取最后一个点
            String suffix = filePath.substring(filePath.lastIndexOf("."));
            //判断是不是class后缀
            if (suffix.equals(".class")) {
                //判断后缀后要开始Class.forName  加载到class对象 在解析对应的注解
                //获取权限名字 com\controller\TestController.class
                String classPath = filePath.replace(new File(PROJECTPATH).getPath() + "\\", "");
                // com.controller.TestController
                classPath = classPath.replaceAll("\\\\", ".");
                String className = classPath.substring(0, classPath.lastIndexOf("."));
                try {
                    //
                    Class<?> clazz = Class.forName(className);
                    //判断是不是加了@controller注解
                    if (clazz.isAnnotationPresent(Controller.class)) {
                        //解析是否加了@RequestMapping
                        RequestMapping classRequestMapping = clazz.getAnnotation(RequestMapping.class);
                        String classRequestMappingUrl = "";
                        //如果不为空赋值
                        if (classRequestMapping != null) {
                            classRequestMappingUrl = classRequestMapping.value();
                        }
                        //遍历所有的方法
                        for (Method method : clazz.getDeclaredMethods()) {
                            //判断是不合成方法
                            if (!method.isSynthetic()) {
                                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                                //加了@RequestMapping 不为空
                                if (annotation != null) {
                                    String methodRequsetMappingUrl = "";
                                    methodRequsetMappingUrl = annotation.value();
                                    System.out.println("类:" + clazz.getName() + "的" + method.getName() + "方法被映射到了" + classRequestMappingUrl + methodRequsetMappingUrl + "上面");
                                    //取到对应的将路径加起来放到一个map中去
                                    methodMap.put(classRequestMappingUrl + methodRequsetMappingUrl, method);
                                }
                            }
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

注解  自定义注解和springmvc注解一样
@Target(ElementType.TYPE)//只能加在类上面
@Retention(RetentionPolicy.RUNTIME)//生命周期
public @interface Controller {
}
@Target({ElementType.TYPE,ElementType.METHOD}) //加载在类和方法上面
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
    /**
     * url 的拦截地址
     * @return
     */
    String value() default "";
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseBody {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值