一步一步教你手写SpringMvc框架,让别人对你刮目相看!
ccwgpt 2024-09-26 07:49 44 浏览 0 评论
1.首先定义几个常用的注解
自定义service注解: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DyService { String value() default ""; } 自定义Autowired注解: @Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DyAutowired { String value() default ""; } 自定义Controller注解: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DyController { String value() default ""; } 自定义RequestMapping注解: @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DyRequestMapping { public String value() default ""; } 自定义RequestParam注解: @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DyRequestParam { String value() default ""; }
2.定义工具类扫描包路径,解析xml文件
/** * 通用的工具类 */ public class CommonUtils { /** * 获取扫描的基础包名 * @param contextConfigLocation * @return * @throws Exception */ public static String getBasePackName(String contextConfigLocation) throws Exception { //读取xml配置文件 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream inputStream = CommonUtils.class.getClassLoader().getResourceAsStream(contextConfigLocation); Document document = builder.parse(inputStream); //开始解析 Element root = document.getDocumentElement(); NodeList childNodes = root.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if(node instanceof Element) { Element element=(Element)node; String attribute = element.getAttribute("base-package"); if(attribute!=null || !"".equals(attribute.trim())) { return attribute.trim(); } } } return null; } /** * 将限定名转换为路径,如pers.hdh -> pers/hdh * @param qualifiedName * @return * @throws Exception */ public static String transferQualifiedToPath(String qualifiedName) throws Exception { if(qualifiedName==null) { throw new Exception("空串不可转换"); } return qualifiedName.replaceAll("\\.","/"); } /** * 转换第一个字母为小写 * @param simpleName * @return */ public static String toLowerFirstWord(String simpleName) { char[] charArray = simpleName.toCharArray(); charArray[0] += 32; return String.valueOf(charArray); } public static void main(String[] args) throws Exception{ System.out.println(transferQualifiedToPath(getBasePackName("dy-springmvc.xml"))); } }
3.定义UserService接口:
public interface UserService { String getPersonInfo(String name,String age); }
4.定义UserServiceImpl实现:
@DyService("userService") public class UserServiceImpl implements UserService{ public String getPersonInfo(String name, String age) { return name+"-"+age; } }
5.自定义DispatcherServlet:
@SuppressWarnings("serial") public class DyDispatcherServlet extends HttpServlet{ // 集合全自动扫描基础包下面的类限定名 private List<String> beanNames=new ArrayList<String>(); // 缓存 key/value: 类注解参数/类实例对象,存储controller和service实例 private Map<String, Object> instanceMaps=new HashMap<String, Object>(); // key/value: 请求url/handler的method private Map<String, Method> handlerMaps = new HashMap<String, Method>(); // 再维护一个map,存储controller实例 private Map<String, Object> controllerMaps = new HashMap<String, Object>(); @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 { try { doDispatch(req, resp); } catch (Exception e) { e.printStackTrace(); } } /** * 处理业务 * @param req * @param resp */ private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception { String uri = req.getRequestURI();// 如:/project_name/classURI/methodURI String contextPath = req.getContextPath();// 如:/project_name String url=uri.replace(contextPath,"").replace("/+", "/"); // 获取到请求执行的方法 Method method = handlerMaps.get(url); PrintWriter out = resp.getWriter(); if(method==null) { out.print("404!!!您访问的资源不存在"); return; } // 获取方法的参数列表 Parameter[] methodParameters = method.getParameters(); // 调用方法需要传递的形参 Object paramValues[]=new Object[methodParameters.length]; for (int i = 0; i < methodParameters.length; i++) { if(ServletRequest.class.isAssignableFrom(methodParameters[i].getType())) { paramValues[i]=req; }else if(ServletResponse.class.isAssignableFrom(methodParameters[i].getType())) { paramValues[i]=resp; }else { // 其它参数,目前只支持String,Integer,Float,Double // 参数绑定的名称,默认为方法形参名 String bindName = methodParameters[i].getName(); if(methodParameters[i].isAnnotationPresent(DyRequestParam.class)) { bindName=methodParameters[i].getAnnotation(DyRequestParam.class).value(); } // 从请求中获取参数的值 String parameterValue = req.getParameter(bindName); paramValues[i]=parameterValue; if(parameterValue!=null) { if(Integer.class.isAssignableFrom(methodParameters[i].getType())) { paramValues[i]=Integer.parseInt(parameterValue); }else if(Float.class.isAssignableFrom(methodParameters[i].getType())) { paramValues[i]=Float.parseFloat(parameterValue); }else if(Double.class.isAssignableFrom(methodParameters[i].getType())) { paramValues[i]=Double.parseDouble(parameterValue); } } } } method.invoke(controllerMaps.get(url), paramValues); } @Override public void init(ServletConfig config) throws ServletException { // 1.通过web.xml拿到基本包信息 读外部配置文件 String mvcConfig = config.getInitParameter("contextConfigLocation") .replace("*:","").replace("classpath",""); try { String basePackName = CommonUtils.getBasePackName(mvcConfig); System.out.println("扫描的基包是:"+basePackName); // 2.全自动扫描基本包下的bean,加载Spring容器 scanPack(basePackName); // 3.通过注解对象,找到每个bean,反射获取实例 reflectBeansInstance(); // 4.依赖注入,实现ioc机制 doIoc(); // 5.handlerMapping通过基部署 和 基于类的url找到相应的处理器 initHandlerMapping(); } catch (Exception e) { e.printStackTrace(); } } /** * 扫描基本包 * @param basePackName * @throws Exception */ private void scanPack(String basePackName) throws Exception { URL url = this.getClass().getClassLoader().getResource("/"+CommonUtils.transferQualifiedToPath(basePackName)); //读取到扫描包 File dir=new File(url.getFile()); File[] files = dir.listFiles(); for (File file : files) { if(file.isDirectory()) {//如果是目录递归读取 scanPack(basePackName+"."+file.getName()); }else if(file.isFile()) { beanNames.add(basePackName+"."+file.getName().replace(".class","")); System.out.println("扫描到的类有:" + basePackName + "." + file.getName().replace(".class", "")); } } } /** * 通过注解对象,找到每个bean,反射获取实例 * @throws Exception */ private void reflectBeansInstance() throws Exception { if(beanNames.isEmpty()) { return; } for (String className : beanNames) { Class<?> clazz = Class.forName(className); if(clazz.isAnnotationPresent(DyController.class)) {// 操作控制层的实例 Object newInstance = clazz.newInstance(); DyController dyController = clazz.getAnnotation(DyController.class); String key = dyController.value(); if("".equals(key)) {//如果使用@DhController,@DhService没有配置value的值,默认使用类名 首字母小写 key= CommonUtils.toLowerFirstWord(clazz.getSimpleName()); } instanceMaps.put(key,newInstance); }else if(clazz.isAnnotationPresent(DyService.class)) {// 操作业务层的实例 Object newInstance = clazz.newInstance(); DyService dyService = clazz.getAnnotation(DyService.class); String key = dyService.value(); if("".equals(key)) { key=CommonUtils.toLowerFirstWord(clazz.getSimpleName()); } instanceMaps.put(key, newInstance); } } } /** * 依赖注入,实现ioc机制 * @throws Exception */ private void doIoc() throws Exception { if(instanceMaps.isEmpty()) { throw new Exception("没有发现可注入的实例"); } for (Map.Entry<String, Object> entry : instanceMaps.entrySet()) { Field[] fields = entry.getValue().getClass().getDeclaredFields(); //遍历bean上的字段 for (Field field : fields) { if(field.isAnnotationPresent(DyAutowired.class)) { // 通过bean字段对象上面的注解参数来注入实例 String insMapKey = field.getAnnotation(DyAutowired.class).value(); //如果使用@DhController,@DhService没有配置value的值,默认使用类名 首字母小写 if("".equals(insMapKey)) { insMapKey=CommonUtils.toLowerFirstWord(field.getType().getSimpleName()); } field.setAccessible(true); field.set(entry.getValue(),instanceMaps.get(insMapKey)); } } } } /** * 通过对请求url分析之后拿到响应的handler实例里面的method处理 * @throws Exception */ private void initHandlerMapping() throws Exception { if(instanceMaps.isEmpty()) { throw new Exception("没有发现handler对象"); } for (Map.Entry<String, Object> entry : instanceMaps.entrySet()) { Class<? extends Object> clazz = entry.getValue().getClass(); // 通过实例区分Controller层对象 if(clazz.isAnnotationPresent(DyController.class)) { // 实现注解映射请求路径,允许当controller类没有使用@DhRequestMapping注解时, // 可使用@DhController注解的value作为请求路径 String uri=""; if(clazz.isAnnotationPresent(DyRequestMapping.class)) { uri=clazz.getAnnotation(DyRequestMapping.class).value(); }else { uri=clazz.getAnnotation(DyController.class).value(); } // 遍历controller类中每个使用@DhRquestMapping的方法,细化请求路径 Method[] methods = clazz.getMethods(); for (Method method : methods) { if(method.isAnnotationPresent(DyRequestMapping.class)) { String methodURI = method.getAnnotation(DyRequestMapping.class).value(); // String url=("/"+uri+"/"+methodURI).replace("/+","/"); String url=uri+methodURI; handlerMaps.put(url, method); // 再维护一个只存储controller实例的map controllerMaps.put(url, entry.getValue()); } } } } } }
6.配置dy-springmvc.xml:
<beans> <!-- 配置扫描包 --> <context:component-scan base-package="com.enjoy"></context:component-scan> </beans>
7.定义web.xml文件:
<servlet> <servlet-name>mvc</servlet-name> <servlet-class>com.enjoy.servlet.DyDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:dy-springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
8.测试自定义的SpringMvc框架
@DyController @DyRequestMapping("/test") public class TestController { @DyAutowired private UserService userService; @DyRequestMapping("/mvc") public void testMvc(HttpServletRequest request, HttpServletResponse response, @DyRequestParam("name")String name,@DyRequestParam("age")Integer age) throws IOException { String personInfo = userService.getPersonInfo(name, age+""); PrintWriter writer = response.getWriter(); writer.write(personInfo); } }
上面的大功告成,是不是没有想的那么复杂。觉得有帮助的同学,请留个言,点个关注,后续会有更多内容分享,谢谢。
相关推荐
- 滨州维修服务部“一区一策”强服务
-
今年以来,胜利油田地面工程维修中心滨州维修服务部探索实施“一区一策”服务模式,持续拓展新技术应用场景,以优质的服务、先进的技术,助力解决管理区各类维修难题。服务部坚持问题导向,常态化对服务范围内的13...
- 谷歌A2A协议和MCP协议有什么区别?A2A和MCP的差异是什么?
-
在人工智能的快速发展中,如何实现AI模型与外部系统的高效协作成为关键问题。谷歌主导的A2A协议(Agent-to-AgentProtocol)和Anthropic公司提出的MCP协议(ModelC...
- 谷歌大脑用架构搜索发现更好的特征金字塔结构,超越Mask-RCNN等
-
【新智元导读】谷歌大脑的研究人员发表最新成果,他们采用神经结构搜索发现了一种新的特征金字塔结构NAS-FPN,可实现比MaskR-CNN、FPN、SSD更快更好的目标检测。目前用于目标检测的最先...
- 一文彻底搞懂谷歌的Agent2Agent(A2A)协议
-
前段时间,相信大家都被谷歌发布的Agent2Agent开源协议刷屏了,简称A2A。谷歌官方也表示,A2A是在MCP之后的补充,也就是MCP可以强化大模型/Agent的能力,但每个大模型/Agent互为...
- 谷歌提出创新神经记忆架构,突破Transformer长上下文限制
-
让AI模型拥有人类的记忆能力一直是学界关注的重要课题。传统的深度学习模型虽然在许多任务上取得了显著成效,但在处理需要长期记忆的任务时往往力不从心。就像人类可以轻松记住数天前看过的文章重点,但目前的...
- 不懂设计?AI助力,人人都能成为UI设计师!
-
最近公司UI资源十分紧张,急需要通过AI来解决UI人员不足问题,我在网上发现了几款AI应用非常适合用来进行UI设计。以下是一些目前非常流行且功能强大的工具,它们能够提高UI设计效率,并帮助设计师创造出...
- 速来!手把手教你用AI完成UI界面设计
-
晨星技术说晨星技术小课堂第二季谭同学-联想晨星用户体验设计师-【晨星小课堂】讲师通过简单、清晰的语言描述就能够用几十秒自动生成一组可编辑的UI界面,AIGC对于UI设计师而言已经逐步发展成了帮助我们...
- 「分享」一端录制,多端使用的便捷 UI 自动化测试工具,开源
-
一、项目介绍Recorder是一款UI录制和回归测试工具,用于录制浏览器页面UI的操作。通过UIRecorder的录制功能,可以在自测的同时,完成测试过程的录制,生成JavaScr...
- APP自动化测试系列之Appium介绍及运行原理
-
在面试APP自动化时,有的面试官可能会问Appium的运行原理,以下介绍Appium运行原理。Appium介绍Appium概念Appium是一个开源测试自动化框架,可用于原生,混合和移动Web应用程序...
- 【推荐】一个基于 SpringBoot 框架开发的 OA 办公自动化系统
-
如果您对源码&技术感兴趣,请点赞+收藏+转发+关注,大家的支持是我分享最大的动力!!!项目介绍oasys是一个基于springboot框架开发的OA办公自动化系统,旨在提高组织的日常运作和管理...
- 自动化实践之:从UI到接口,Playwright给你全包了!
-
作者:京东保险宋阳1背景在车险系统中,对接保司的数量众多。每当系统有新功能迭代后,基本上各个保司的报价流程都需要进行回归测试。由于保司数量多,回归测试的场景也会变得重复而繁琐,给测试团队带来了巨大的...
- 销帮帮CRM移动端UI自动化测试实践:Playwright的落地与应用
-
实施背景销帮帮自2015年成立以来,移动端UI自动化测试的落地举步维艰,移动端的UI自动化测试一直以来都未取得良好的落地。然而移动互联网时代,怎样落地移动端的UI自动化测试以快速稳定进行移动端的端到端...
- 编写自动化框架不知道该如何记录日志吗?3个方法打包呈现给你。
-
目录结构1.loguru介绍1.1什么是日志?程序运行过程中,难免会遇到各种报错。如果这种报错是在本地发现的,你还可以进行debug。但是如果程序已经上线了,你就不能使用debug方式了...
- 聊聊Python自动化脚本部署服务器全流程(详细)
-
来源:AirPython作者:星安果1.前言大家好,我是安果!日常编写的Python自动化程序,如果在本地运行稳定后,就可以考虑将它部署到服务器,结合定时任务完全解放双手但是,由于自动化程序与平...
- 「干货分享」推荐5个可以让你事半功倍的Python自动化脚本
-
作者:俊欣来源:关于数据分析与可视化相信大家都听说自动化流水线、自动化办公等专业术语,在尽量少的人工干预的情况下,机器就可以根据固定的程序指令来完成任务,大大提高了工作效率。今天小编来为大家介绍几个P...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- MVC框架 (46)
- spring框架 (46)
- 框架图 (58)
- flask框架 (53)
- quartz框架 (51)
- abp框架 (47)
- jpa框架 (47)
- springmvc框架 (49)
- 分布式事务框架 (65)
- scrapy框架 (56)
- shiro框架 (61)
- 定时任务框架 (56)
- java日志框架 (61)
- JAVA集合框架 (47)
- mfc框架 (52)
- abb框架断路器 (48)
- ui自动化框架 (47)
- grpc框架 (55)
- ppt框架 (48)
- 内联框架 (52)
- cad怎么画框架 (58)
- ps怎么画框架 (47)
- ssm框架实现登录注册 (49)
- oracle字符串长度 (48)
- oracle提交事务 (47)