百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

一步一步教你手写SpringMvc框架,让别人对你刮目相看!

ccwgpt 2024-09-26 07:49 42 浏览 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);
	}
	
}

上面的大功告成,是不是没有想的那么复杂。觉得有帮助的同学,请留个言,点个关注,后续会有更多内容分享,谢谢。

相关推荐

Java七大热门技术框架源码解析(25章) 完结

获课》aixuetang.xyz/5699/Hibernate与MyBatis源码级PK:ORM框架的两种哲学在Java持久层框架领域,Hibernate与MyBatis代表了两种截然不同的设计哲学。...

【25章】Java七大热门技术框架源码解析

获课》aixuetang.xyz/5699/Java高级面试:七大框架源码精讲与实战解析在当今Java技术生态中,对主流框架源码的深入理解已成为高级开发者面试的核心竞争力。掌握Spring、MyBat...

饿了么董事长吴泽明兼任CEO,韩鎏分管即时物流中心

饿了么调整组织架构。2月11日,饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴泽明汇报。吴泽明...

饿了么100%迁至阿里云,快速扩容可支持1亿人同时点单

来源:环球网6月17日,记者获悉,饿了么已完成100%上云,所有业务系统、数据库设施等均已迁移至阿里云。高峰期,饿了么可在阿里云上快速扩容,可以支持1亿人同时在线点单,这意味着饿了么的服务能力再次全面...

饿了么组织架构调整:董事长吴泽明兼任CEO 韩鎏专注即时物流中心管理

近日,饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴泽明汇报。吴泽明在内部信中表示,考虑即时物...

饿了么组织架构调整:董事长吴泽明兼任CEO

Tech星球2月11日消息,据新浪科技报道,今日饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴...

饿了么又调整了组织架构,董事长吴泽明兼任CEO

2月11日,饿了么董事长,花名为范禹的吴泽明,通过公司全员信宣布最新组织调整:从即日起,吴泽明将兼任饿了么CEO。公司原CEO,花名为昊宸的韩鎏今后专注分管即时物流中心,继续向吴泽明汇报。在内部信中,...

SpringBoot项目快速开发框架JeecgBoot——Web处理!

Web处理JeecgBoot框架主要用于Web开发领域。下面介绍JeecgBoot在Web开发中的常用功能,如控制器、登录、系统菜单、权限模块的角色管理和用户管理。首先启动后台项目,将其导入IDE...

腾讯即将开源Kuikly:基于Kotlin的纯原生跨端解决方案

IT之家3月4日消息,腾讯日前在端服务网站发布预告,即将开源Kuikly跨端开发框架。预告海报介绍称,Kuikly是基于KotlinKMM技术、客户端开发友好的全新跨端解决方案,可...

Python构建MCP服务器完整教程:5步打造专属AI工具调用系统

模型控制协议(ModelControlProtocol,MCP)是一种专为实现AI代理与工具解耦而设计的通信协议,为AI驱动应用程序的开发提供了高度的灵活性和模块化架构。通过MCP服务器,AI代...

Python3使用diagrams生成架构图(python模块制作)

目录技术背景diagrams的安装基础逻辑关系图组件簇的定义总结概要参考链接技术背景对于一个架构师或者任何一个软件工程师而言,绘制架构图都是一个比较值得学习的技能。这就像我们学习的时候整理的一些Xmi...

Python 失宠!Hugging Face 用 Rust 新写了一个 ML框架,现已低调开源

大数据文摘受权转载自AI前线整理|褚杏娟近期,HuggingFace低调开源了一个重磅ML框架:Candle。Candle一改机器学习惯用Python的做法,而是Rust编写,重...

Python Web 框架(Python Web 框架)

Tornado、Flask、Django三个PythonWeb框架的主要区别和适用场景:特点/框架TornadoFlaskDjango类型异步非阻塞Web服务器和框架轻量级微框架全功能...

构建并发布你的自定义 Python 包(python如何创建自定义模块)

Python让你可以重用代码,并将代码分享给他人以节省时间和精力。所以,当你编写了一些方便的脚本,希望你的同事或其他人也能使用时,接下来该怎么做呢?这篇文章就来解决打包和分发的问题。我们将专注于将你...

Python 应用开发框架 BeeWare 简明实用教程

1.BeeWare简介BeeWare是一个Python框架,用于开发跨平台原生应用。它支持Android、iOS、Windows、macOS和Linux,并提供原生用户体验。2.安装B...

取消回复欢迎 发表评论: