文档章节

一个简单的MVC模型实现

蓝汀华韶
 蓝汀华韶
发布于 2017/05/22 17:15
字数 1017
阅读 22
收藏 3

源码地址:https://github.com/shawntime/springmvc-tutorial/tree/master/02-simple-mvc

一个简单的MVC模型实现

自定义实现一个简单的mvc模型,使用效果如下

package com.shawntime.simplemvc.controller;

import javax.servlet.http.HttpServletRequest;

import com.shawntime.simplemvc.annotation.Controller;
import com.shawntime.simplemvc.annotation.RequestMapping;
import com.shawntime.simplemvc.annotation.RequestParameter;
import com.shawntime.simplemvc.entity.User;

/**
 * Created by shma on 2017/5/21.
 */
@Controller(url = "/user")
public class LoginController {

    @RequestMapping(url = "/login", method = "POST")
    public String login(@RequestParameter(value = "userName")String userName,
                        @RequestParameter(value = "password")String password,
                        HttpServletRequest request) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        return "success:" + user;
    }
}

定义注解

package com.shawntime.simplemvc.annotation;

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

/**
 * Created by shma on 2017/5/21.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
    String url() default "";
}

package com.shawntime.simplemvc.annotation;

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

/**
 * Created by shma on 2017/5/21.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
    String url() default "";
    String method() default "GET";
}

package com.shawntime.simplemvc.annotation;

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

/**
 * Created by shma on 2017/5/21.
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestParameter {
    String value() default "";
}

定义ServletContextListener监听,启动服务时会扫描controller包下所有类和方法,生成相关映射关系保存到ServletContext中

package com.shawntime.simplemvc.listener;

import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


/**
 * Created by shma on 2017/5/21.
 */
public class ControllerHandleListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        String packageName = servletContext.getInitParameter("scanPackageName");
        Map<String, MappingBean> mappingBeanMap = ControllerHandler.handle(packageName);
        servletContext.setAttribute("methodHandlerMap", mappingBeanMap);
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // ----
    }
}

package com.shawntime.simplemvc.listener;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.shawntime.simplemvc.annotation.Controller;
import com.shawntime.simplemvc.annotation.RequestMapping;
import com.shawntime.simplemvc.annotation.RequestParameter;
import com.shawntime.simplemvc.utils.PackageUtil;
import org.apache.commons.collections4.CollectionUtils;

/**
 * Created by shma on 2017/5/21.
 */
public final class ControllerHandler {

    public static final Map<String, MappingBean> handle(String packageName) {
        Map<String, MappingBean> dataMap = Maps.newHashMap();
        List<String> classNameList = PackageUtil.getClassName(packageName);
        if (CollectionUtils.isNotEmpty(classNameList)) {
            for (String className : classNameList) {
                try {
                    Map<String, MappingBean> mappingBean = getMappingBean(className);
                    dataMap.putAll(mappingBean);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return dataMap;
    }

    private static Map<String, MappingBean> getMappingBean(String className) throws ClassNotFoundException {
        Map<String, MappingBean> resultMap = Maps.newHashMap();
        Class<?> aClass = Class.forName(className);
        Controller controller = aClass.getAnnotation(Controller.class);
        String headerUrl = controller.url();
        Method[] methods = aClass.getDeclaredMethods();
        if (methods != null && methods.length > 0) {
            for (Method method : methods) {
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String url = headerUrl + requestMapping.url();
                String requestType = requestMapping.method();
                List<ParamBean> paramBeans = loadParam(method);
                MappingBean mappingBean = new MappingBean();
                mappingBean.setUrl(className);
                mappingBean.setMethodType(requestType);
                mappingBean.setMethodName(method.getName());
                mappingBean.setParamBeanList(paramBeans);
                mappingBean.setClazz(method.getParameterTypes());
                resultMap.put(url, mappingBean);
            }
        }
        return resultMap;

    }

    private static List<ParamBean> loadParam(Method method) {
        List<ParamBean> paramBeanList = Lists.newArrayList();
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            ParamBean paramBean = new ParamBean();
            RequestParameter annotation = parameter.getAnnotation(RequestParameter.class);
            if (annotation != null) {
                paramBean.setParamName(annotation.value());
            }
            paramBean.setParamType(parameter.getType());
            paramBeanList.add(paramBean);
        }
        return paramBeanList;
    }
}

package com.shawntime.simplemvc.listener;

import java.util.List;

/**
 * Created by shma on 2017/5/21.
 */
public class MappingBean {

    private String url;

    private String methodName;

    private String methodType;

    private Class<?>[] clazz;

    private List<ParamBean> paramBeanList;

    public Class<?>[] getClazz() {
        return clazz;
    }

    public void setClazz(Class<?>[] clazz) {
        this.clazz = clazz;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public String getMethodType() {
        return methodType;
    }

    public void setMethodType(String methodType) {
        this.methodType = methodType;
    }

    public List<ParamBean> getParamBeanList() {
        return paramBeanList;
    }

    public void setParamBeanList(List<ParamBean> paramBeanList) {
        this.paramBeanList = paramBeanList;
    }
}

package com.shawntime.simplemvc.listener;

/**
 * Created by shma on 2017/5/22.
 */
public class ParamBean {

    private String paramName;

    private Class<?> paramType;

    public String getParamName() {
        return paramName;
    }

    public void setParamName(String paramName) {
        this.paramName = paramName;
    }

    public Class<?> getParamType() {
        return paramType;
    }

    public void setParamType(Class<?> paramType) {
        this.paramType = paramType;
    }
}

创建DispatcherServlet调度

package com.shawntime.simplemvc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shawntime.simplemvc.listener.MappingBean;
import com.shawntime.simplemvc.listener.ParamBean;
import com.shawntime.simplemvc.utils.UriUtil;

/**
 * Created by shma on 2017/5/22.
 */
public class DispatcherServlet extends HttpServlet {

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

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

    private void doParse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, MappingBean> mappingBeanMap =
                (Map<String, MappingBean>) this.getServletContext().getAttribute("methodHandlerMap");
        String uri = UriUtil.getUri(req.getContextPath(), req.getRequestURI().toString());
        if (uri.equals("/")) {
            return;
        }
        MappingBean mappingBean = mappingBeanMap.get(uri);
        if (mappingBean == null) {
            PrintWriter writer = resp.getWriter();
            writer.write("请求url不存在");
            writer.flush();
        }
        try {
            Class<?> aClass = Class.forName(mappingBean.getUrl());
            Method method = aClass.getDeclaredMethod(mappingBean.getMethodName(), mappingBean.getClazz());
            Object object = aClass.newInstance();
            Object[] params = getParams(mappingBean.getParamBeanList(), req);
            Object invoke = method.invoke(object, params);
            PrintWriter writer = resp.getWriter();
            writer.write(invoke.toString());
            writer.flush();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static Object[] getParams(List<ParamBean> paramBeanList, HttpServletRequest request) {
        Object[] paramObj = new Object[paramBeanList.size()];
        for (int i = 0; i < paramBeanList.size(); ++i) {
            String paramName = paramBeanList.get(i).getParamName();
            Class<?> paramType = paramBeanList.get(i).getParamType();
            if (paramType.isInstance(request)) {
                paramObj[i] = request;
            } else {
                paramObj[i] = request.getParameter(paramName);
            }
        }
        return paramObj;
    }
}

package com.shawntime.simplemvc.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PackageUtil {

    public static void main(String[] args) {
        String packageName = "com.shawntime.simplemvc.controller";

        List<String> classNames = getClassName(packageName);
        for (String className : classNames) {
            System.out.println(className);
        }
    }

    public static List<String> getClassName(String packageName) {
        String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + packageName.replace(".", "\\");
        List<String> fileNames = getClassName(filePath, null);
        return fileNames;
    }

    private static List<String> getClassName(String filePath, List<String> className) {
        List<String> myClassName = new ArrayList<String>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                myClassName.addAll(getClassName(childFile.getPath(), myClassName));
            } else {
                String childFilePath = childFile.getPath();
                childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
                childFilePath = childFilePath.replace("\\", ".");
                myClassName.add(childFilePath);
            }
        }

        return myClassName;
    }
}

package com.shawntime.simplemvc.utils;

/**
 * Created by shma on 2017/5/22.
 */
public final class UriUtil {

    private UriUtil() {
        // -----
    }

    public static String getUri(String contextPath, String uri) {
        if (uri.contains("?")) {
            return uri.substring(contextPath.length(), uri.indexOf("?"));
        } else {
            return uri.substring(contextPath.length(), uri.length());
        }
    }
}

web.xml配置

<!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>

    <context-param>
        <param-name>scanPackageName</param-name>
        <param-value>com.shawntime.simplemvc.controller</param-value>
    </context-param>
    
    <listener>
        <listener-class>com.shawntime.simplemvc.listener.ControllerHandleListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>com.shawntime.simplemvc.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>scanPackageName</param-name>
            <param-value>com.shawntime.simplemvc.controller</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

© 著作权归作者所有

共有 人打赏支持
蓝汀华韶
粉丝 36
博文 77
码字总数 80082
作品 0
海淀
程序员
「译」JavaScript 的 MVC 模式

原文:Model-View-Controller (MVC) with JavaScript 作者:Alex@Net 译文:JavaScript 的 MVC 模式 译者:justjavac 本文介绍了模型-视图-控制器模式在 JavaScript 中的实现。 我喜欢 Java...

justjavac
2012/12/18
3.9K
9
为什么要使用MVC+REST+CQRS架构

具体来说,前端浏览器:angular.js等MVC框架;后端: REST+ CQRS。 angular.js等MVC框架是指前端浏览器的MVC框架,而不是类似Struts 或SpringMVC之类的服务器端后端MVC框架。 关于后端MVC框架...

天衣无缝
2013/08/09
0
0
MVC真的适合PHP吗?

MVC的原型 MVC本来是存在于Desktop程序中的,M是指数据模型,V是指用户界面,C则是控制器。使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如一批统计数据...

旋转木马-千里马
2016/01/21
36
0
iOS架构模式MVC+MVP+mvvm架构

随着iOS职位的火热,越来越多的人都想成为一名优秀的iOS开发工程师,那么在竞争激烈的时代,应该如何成为一名iOS开发工程师呢?现在让大家了解一下iOS架构模式 作为一个开发者,有一个学习的...

iOS晓雯
06/24
0
0
设计模式(1)—— MVC

MVC(Model-View-Controller,模型-视图-控制器)是软件工程中的一种软件架构模式,它把软件系统分为三个基本部分:模型(Model)、视图(View)、控制器(Controller)。 MVC不是一种设计模...

长平狐
2013/01/06
1K
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

人生苦短:Python里的17个“超赞操作

人生苦短,我选Python”。那么,你真的掌握了Python吗? 1. 交换变量 有时候,当我们要交换两个变量的值时,一种常规的方法是创建一个临时变量,然后用它来进行交换。比如: # 输入 a = 5 b ...

糖宝lsh
45分钟前
4
0
咕泡-spring中常用设计模式概述

设计模式就是经验之谈,供后人借鉴,解决一些具有代表性的问题 设计模式来源于生活,反过来帮助我们更好生活 设计模式提升代码的可读性、可扩展性、维护成本、复杂业务问题 千万不要死记硬背...

职业搬砖20年
今天
2
0
day59-20180817-流利阅读笔记-待学习

假·照骗,真·社交焦虑 雪梨 2018-08-17 1.今日导读 发朋友圈之前,不少人为了展现更美好的生活状态会对照片加以“微调”,或是加个滤镜显得逼格更高,或是磨个皮瘦个脸拉个大长腿。现在,国...

aibinxiao
今天
23
0
OSChina 周五乱弹 —— 姑娘在这个节日里表白你接受么?

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @Sharon啊:完全被这个小姐姐圈粉了,学两首她的歌去哈哈 分享王贰浪的单曲《往后余生(翻自 马良)》 《往后余生(翻自 马良)》- 王贰浪 手...

小小编辑
今天
1K
16
为什么HashMap要自己实现writeObject和readObject方法?

为什么HashMap要自己实现writeObject和readObject方法? 如果你有仔细阅读过HashMap的源码,那么你一定注意过一个问题:HashMap中有两个私有方法。 private void writeObject(java.io.Objec...

DemonsI
今天
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部