[后端java学习] 自己写一个简单的springMvc

写完spring后,又研究了一下SpringMvc,这里实现并记录一下。

 项目地址:GitHub - liulint/MySpringMvc

在看这个之前,可以先看一下我写的Spring,地址:[后端java学习] 自己写一个简单的spring-CSDN博客

标红框的,为新添加的文件

1.准备工作

引入servlet依赖

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

添加Controller,RequestMapping注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Controller {
    @AliasFor(annotation = Component.class)
    String value() default "";
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestMapping {

    String value() default "";

    RequestMethod[] method() default {};
}

添加RequestMethod枚举

public enum RequestMethod {
    GET,
    HEAD,
    POST,
    PUT,
    PATCH,
    DELETE,
    OPTIONS,
    TRACE;

    private RequestMethod() {
    }
}

编写DispatchServlet类

public class MyDispatcherServlet extends HttpServlet {

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

    private Map<String, RequestMethod[]> requestMethodsMap = new HashMap<>();
    private Map<String, Object> controllerMap  =new HashMap<>();
    MyApplicationContext myApplicationContext;
    @Override
    public void init() throws ServletException {
        myApplicationContext = new MyApplicationContext(SpringConfig.class);
        //初始化HandlerMapping(将url和method对应上)
        initHandlerMapping();
    }

    @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 {
        resp.setCharacterEncoding("UTF-8");
        try {
            //处理请求
            String s = doDispatch(req, resp);
            resp.getWriter().write(s);
        } catch (Exception e) {
            resp.getWriter().write("500!! Server Exception");
        }

    }




    private String doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if(handlerMapping.isEmpty()){
            return "";
        }
        String reqMethod = req.getMethod();
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();

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

        if(!this.handlerMapping.containsKey(url)){
            return "404 NOT FOUND!";
        }

        RequestMethod[] requestMethods = requestMethodsMap.get(url);
        Optional<RequestMethod> reqMethodResult = Arrays.stream(requestMethods).filter(requestMethod -> requestMethod.toString().equals(reqMethod)).findFirst();
        if(!reqMethodResult.isPresent()){
            return "Request method not supported";
        }

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

        //获取方法的参数列表
        Class<?>[] parameterTypes = method.getParameterTypes();

        //获取请求的参数
        Map<String, String[]> parameterMap = req.getParameterMap();

        //保存参数值
        Object [] paramValues= new Object[parameterTypes.length];

        //方法的参数列表
        for (int i = 0; i<parameterTypes.length; i++){
            //根据参数名称,做某些处理
            String requestParam = parameterTypes[i].getSimpleName();
            if (requestParam.equals("HttpServletRequest")){
                //参数类型已明确,这边强转类型
                paramValues[i]=req;
                continue;
            }
            if (requestParam.equals("HttpServletResponse")){
                paramValues[i]=resp;
                continue;
            }
        }
        //利用反射机制来调用
        Object invoke = null;
        try {
            invoke = method.invoke(this.controllerMap.get(url), paramValues);//第一个参数是method所对应的实例 在ioc容器中
        } catch (Exception e) {
            e.printStackTrace();
        }
        return invoke.toString();
    }

    private void initHandlerMapping(){
        Map<String, BeanDefinition> controllerBeanDefinitionMap = myApplicationContext.controllerBeanDefinitionMap;
        if(controllerBeanDefinitionMap.isEmpty()){
            return;
        }
        try {
            for (Map.Entry<String, BeanDefinition> entry: controllerBeanDefinitionMap.entrySet()) {
                BeanDefinition beanDefinition = entry.getValue();
                Class<? extends Object> clazz = beanDefinition.getType();
                //拼url时,是controller头的url拼上方法上的url
                String baseUrl ="";
                if(clazz.isAnnotationPresent(RequestMapping.class)){
                    RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);
                    baseUrl=annotation.value();
                }
                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods) {
                    if(!method.isAnnotationPresent(RequestMapping.class)){
                        continue;
                    }
                    RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                    String url = annotation.value();
                    RequestMethod[] requestMethods = annotation.method();
                    url =(baseUrl+"/"+url).replaceAll("/+", "/");
                    handlerMapping.put(url,method);
                    Object instance = myApplicationContext.createBean(beanDefinition, entry.getKey());
                    controllerMap.put(url,instance);
                    requestMethodsMap.put(url,requestMethods);
                    System.out.println(url+","+method);
                }

            }

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

    }

}

给maven项目添加web支持,添加web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>MySpringMVC</servlet-name>
    <servlet-class>com.testSpringMvc.MyDispatcherServlet</servlet-class>//自己编写的dispactherServlet类的位置

    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>MySpringMVC</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>

2.测试

编写TestController

@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    @Qualifier("wewefwef")
    OneService oneService;
 
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String test1(HttpServletRequest request, HttpServletResponse response){
      return oneService.test1();
    }
  
  
    @RequestMapping(value = "/test2",method = RequestMethod.POST)
    public String test2(HttpServletRequest request, HttpServletResponse response){
      return "test2方法";
    }
}

运行项目,进行测试

访问test1方法

访问test2方法,因为方式为get,所以报

Request method not supported

使用测试接口工具,通过post方法访问正常

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值