mvc框架图书馆管理系统jdbc mvc架构图用什么画( 四 )


@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {if (methodMap.isEmpty()){return;}String uri = req.getRequestURI();String contextPath = req.getContextPath();//获取有效urlString url = uri.replace(contextPath,"");//如果没有对应的url,返回404if (!methodMap.containsKey(url)){resp.getWriter().println("404");}else {//有的话,通过invoke方法执行对应controller的methodMethod method = methodMap.get(url);Object controller = controllerMap.get(url);try {method.invoke(controller);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}至此,MyDispatcherServlet的所有代码都已经完成了,他也能够成为一个合格的领导了 。
上面部分代码写的较为分散,文末放上MyDispatcherServlet的完整代码供同学们参考
最后,编写一个Controller进行测试package com.cloudwise.controller;/*** @author Teacher 陈* @creat 2021-02-22-14:57* @describ*/import com.cloudwise.annotition.MyController;import com.cloudwise.annotition.MyRequestMapping;/*** @author :Teacher 陈* @date :Created in 2021/2/22 14:57* @description:我的实验性Controller* @modified By:* @version:*/@MyController@MyRequestMapping(value = "https://www.520longzhigu.com/test")public class MyFirstController {@MyRequestMapping(value = "https://www.520longzhigu.com/test1")public void test1(){System.out.println("test1被调用了");}@MyRequestMapping(value = "https://www.520longzhigu.com/test2")public void test2(){System.out.println("test2被调用了");}@MyRequestMapping(value = "https://www.520longzhigu.com/test3")public void test3(){System.out.println("test3被调用了");}}测试1.为本项目配置tomcat
2.运行
3.1浏览器地址栏输入对应网址
控制台成功打印日志信息
3.2浏览器地址栏输入无效网址,页面返回404
至此,今天的手写springMVC就全部完成了 。
当然本项目还有很多待提升的地方,诸如不能返回json数据,controller不能有参数,等等 。但是我们不可能一朝一夕建成罗马,应该一步一个脚印,通过这个项目掌握springMVC的运行流程,为以后更难的项目打下点基础 。
代码(总览)package com.cloudwise.servlet;/*** @author Teacher 陈* @creat 2021-02-22-13:44* @describ*/import com.cloudwise.annotition.MyController;import com.cloudwise.annotition.MyRequestMapping;import org.reflections.Reflections;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.IOException;import java.io.InputStream;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.*;/*** @author :Teacher 陈* @date :Created in 2021/2/22 13:44* @description:我的前端控制器dispather* @modified By:* @version:*/public class MyDispatcherServlet extends HttpServlet {/*** 我们将需要扫描的包放在一个.properties文件中* 需要在初始化的时候读取它*/private Properties properties = new Properties();/*** 我们需要一个Set,将所有能够响应的Controller存起来*/private Set<Class<?>> classSet = new HashSet<>();/*** 类spring-mvc容器,存储Controller对象*/private Map<String,Object> mySpringMVCContext = new HashMap<>();/*** 存储所有方法的Map<url:method>*/private Map<String,Method> methodMap = new HashMap<>();/*** 存储所有Controller的Map*/private Map<String,Object> controllerMap = new HashMap<>();/*** @description: 初始化,要做什么事呢?* 0. 接收到请求之后,首先将后端环境初始化好* 1. 加载配置文件* 2. 扫描controller包* 3. 初始化controller* 4. 初始化Controller映射器* @create by: Teacher 陈* @create time: 2021/2/22 13:47* @param config* @return void*/@Overridepublic void init(ServletConfig config) throws ServletException {//1. 加载配置文件String initParameter = config.getInitParameter("contextConfigLocation");try {loadConfigfile(initParameter);} catch (IOException e) {e.printStackTrace();}//2. 扫描controller包,存储所有能够响应的ControllerscanPackage(properties.getProperty("package"));//3. 初始化controllertry {initController();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}//4. 初始化Controller映射器initHandlerMapping();}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {if (methodMap.isEmpty()){return;}String uri = req.getRequestURI();String contextPath = req.getContextPath();String url = uri.replace(contextPath,"");if (!methodMap.containsKey(url)){resp.getWriter().println("404");}else {Method method = methodMap.get(url);Object controller = controllerMap.get(url);try {method.invoke(controller);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}/*** 以下为工具性函数*//*** 加载配置文件* @param fileName*/private void loadConfigfile(String fileName) throws IOException {//以流的方式获取资源InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);properties.load(resourceAsStream);resourceAsStream.close();}/*** 扫描包,获取所有带MyController的类* @param packageName*/private void scanPackage(String packageName){Reflections reflections = new Reflections(packageName);classSet = reflections.getTypesAnnotatedWith(MyController.class);}/*** 初始化Controller*/private void initController() throws IllegalAccessException, InstantiationException {if(classSet.isEmpty()){return;}for (Class<?> controller : classSet) {mySpringMVCContext.put(firstWordToLowCase(controller.getSimpleName()),controller.newInstance());}}/*** 首字母转小写* @param string* @return 首字母为小写的String*/private String firstWordToLowCase(String string){char[] chars = string.toCharArray();//将大写转成小写chars[0]+=32;return String.valueOf(chars);}private void initHandlerMapping() {if (mySpringMVCContext.isEmpty()){return;}for (Map.Entry<String, Object> entry : mySpringMVCContext.entrySet()) {Class<?> entryClass = entry.getValue().getClass();if (!entryClass.isAnnotationPresent(MyController.class)){continue;}//Controller类上的requestMapping值,如果有则获取String baseUrl = "";if (entryClass.isAnnotationPresent(MyRequestMapping.class)){MyRequestMapping annotation = entryClass.getAnnotation(MyRequestMapping.class);baseUrl = annotation.value();}//获取所有方法Method[] methods = entryClass.getMethods();for (Method method : methods) {if (method.isAnnotationPresent(MyRequestMapping.class)){MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);String url = annotation.value();url = baseUrl + url;//将该方法放入方法集methodMap.put(url,method);//将该controller方法处理器集controllerMap.put(url,entry.getValue());//至此,初始化完成,后端整装待发}}}}}


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: