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

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

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

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

相关推荐

详解DNFSB2毒王的各种改动以及大概的加点框架

首先附上改动部分,然后逐项分析第一个,毒攻掌握技能意思是力量智力差距超过15%的话差距会被强行缩小到15%,差距不到15%则无效。举例:2000力量,1650智力,2000*0.85=1700,则智力...

通篇干货!纵观 PolarDB-X 并行计算框架

作者:玄弟七锋PolarDB-X面向HTAP的混合执行器一文详细说明了PolarDB-X执行器设计的初衷,其初衷一直是致力于为PolarDB-X注入并行计算的能力,兼顾TP和AP场景,逐渐...

字节新推理模型逆袭DeepSeek,200B参数战胜671B,豆包史诗级加强

梦晨发自凹非寺量子位|公众号QbitAI字节最新深度思考模型,在数学、代码等多项推理任务中超过DeepSeek-R1了?而且参数规模更小。同样是MoE架构,字节新模型Seed-Thinkin...

阿里智能化研发起飞!RTP-LLM 实现 Cursor AI 1000 token/s 推理技术揭秘

作者|赵骁勇阿里巴巴智能引擎事业部审校|刘侃,KittyRTP-LLM是阿里巴巴大模型预测团队开发的高性能LLM推理加速引擎。它在阿里巴巴集团内广泛应用,支撑着淘宝、天猫、高德、饿...

多功能高校校园小程序/校园生活娱乐社交管理小程序/校园系统源码

校园系统通常是为学校、学生和教职工提供便捷的数字化管理工具。综合性社交大学校园小程序源码:同城校园小程序-大学校园圈子创业分享,校园趣事,同校跑腿交友综合性论坛。小程序系统基于TP6+Uni-app...

婚恋交友系统nuiAPP前端解决上传视频模糊的问题

婚恋交友系统-打造您的专属婚恋交友平台系统基于TP6+Uni-app框架开发;客户移动端采用uni-app开发,管理后台TH6开发支持微信公众号端、微信小程序端、H5端、PC端多端账号同步,可快速打包...

已节省数百万GPU小时!字节再砍MoE训练成本,核心代码全开源

COMET团队投稿量子位|公众号QbitAI字节对MoE模型训练成本再砍一刀,成本可节省40%!刚刚,豆包大模型团队在GitHub上开源了叫做COMET的MoE优化技术。COMET已应用于字节...

通用电气完成XA102发动机详细设计审查 将为第六代战斗机提供动力

2025年2月19日,美国通用电气航空航天公司(隶属于通用电气公司)宣布,已经完成了“下一代自适应推进系统”(NGAP)计划下提供的XA102自适应变循环发动机的详细设计审查阶段。XA102是通用电气...

tpxm-19双相钢材质(双相钢f60材质)

TPXM-19双相钢是一种特殊的钢材,其独特的化学成分、机械性能以及广泛的应用场景使其在各行业中占有独特的地位。以下是对TPXM-19双相钢的详细介绍。**化学成分**TPXM-19双相钢的主要化学成...

thinkphp6里怎么给layui数据表格输送数据接口

layui官网已经下架了,但是产品还是可以使用。今天一个朋友问我怎么给layui数据表格发送数据接口,当然他是学前端的,后端不怎么懂,自学了tp框架问我怎么调用。其实官方文档上就有相应的数据格式,js...

完美可用的全媒体广告精准营销服务平台PHP源码

今天测试了一套php开发的企业网站展示平台,还是非常不错的,下面来给大家说一下这套系统。1、系统架构这是一套基于ThinkPHP框架开发的HTML5响应式全媒体广告精准营销服务平台PHP源码。现在基于...

一对一源码开发,九大方面完善基础架构

以往的直播大多数都是一对多进行直播社交,弊端在于不能满足到每个用户的需求,会降低软件的体验感。伴随着用户需求量的增加,一对一直播源码开始出现。一个完整的一对一直播流程即主播发起直播→观看进入房间观看→...

Int J Biol Macromol .|交联酶聚集体在分级共价有机骨架上的固定化:用于卤代醇不对称合成的高稳定酶纳米反应器

大家好,今天推送的文章发表在InternationalJournalofBiologicalMacromolecules上的“Immobilizationofcross-linkeden...

【推荐】一款开源免费的 ChatGPT 聊天管理系统,支持PC、H5等多端

如果您对源码&技术感兴趣,请点赞+收藏+转发+关注,大家的支持是我分享最大的动力!!!项目介绍GPTCMS是一款开源且免费(基于GPL-3.0协议开源)的ChatGPT聊天管理系统,它基于先进的GPT...

高性能计算(HPC)分布式训练:训练框架、混合精度、计算图优化

在深度学习模型愈发庞大的今天,分布式训练、高效计算和资源优化已成为AI开发者的必修课。本文将从数据并行vs模型并行、主流训练框架(如PyTorchDDP、DeepSpeed)、混合精度训练(...

取消回复欢迎 发表评论: