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

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

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

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

相关推荐

如何使用PIL生成验证码?(pi验证教程)

web项目中遇到使用验证码的情况有很多,进行介绍下使用PIL生成验证码的方法。安装开始安装PIL的过程确实麻烦各种问题层出不绝,不过不断深入后就没有这方面的困扰了:windows安装:直接安装Pil...

Python必学!3步解锁asyncio异步编程 性能直接狂飙10倍!

还在用传统同步代码被IO阻塞卡到崩溃?别当“代码苦行僧”了!Python的asyncio模块堪称异步编程的“开挂神器”,处理高并发任务就像开了涡轮增压!不管是网络爬虫、API接口开发还是文件批量处理,...

Tornado6+APScheduler/Celery打造并发异步动态定时任务轮询服务

定时任务的典型落地场景在各行业中都很普遍,比如支付系统中,支付过程中因为网络或者其他因素导致出现掉单、卡单的情况,账单变成了“单边账”,这种情况对于支付用户来说,毫无疑问是灾难级别的体验,明明自己付了...

Python学习怎么入门?附真实学习方法

Python技术在企业中应用的越来越广泛,因此企业对于Python方面专业人才的需求也越来越大,那对于之前对Python没有任何了解和接触的人而言,想要从零开始学习并不是一件容易的事情,接下来小U就为...

PySpider框架的使用(pyspider 教程)

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

大学计算机专业 学习Python学习路线图(最新版)

这是我刚开始学习python时的一套学习路线,从入门到上手。(不敢说精通,哈哈~)希望对大家有帮助哈~大家需要高清得完整python学习路线可以【文末有获取方式】【文末有获取方式】一、Python入门...

阿里巴巴打造的400集Python视频合集免费学起来,学完万物皆可爬

第一阶段Python入门章节1:Python入门章节2:编程基本概念章节3:序列章节4:控制语句章节5:函数章节6:面向对象编程第二阶段Python深入与提高章节1:异常处理章节2:游戏开发-坦克大...

Nginx Gunicorn在服务器中分别起什么作用

大部分人在gunicorn前面部署一层nginx的时候也的确没有想过为什么,他们只是觉得这样显得他们比较专业,而且幻想着加了一层nginx反向代理之后性能会有提升,恕我直言,请你们带上脑子,一个单纯的...

Python培训怎么学?Python基础技术总结!值得一看

Python培训如今越来越被更多人所接受,相比自学参加Python培训的好处也是显而易见,但Python毕竟属于后端编程开发的主流语言,其知识机构还是比较庞大的,那Python培训怎么学?以及Pyth...

使用Tornado部署Flask项目(tornado async)

Tornado不仅仅是一个WEB框架,也可以是一个WEB服务器。在Tornado中我们可以使用wsgi模块下的WSGIContainer类运行其他WSGI应用如:Fask,Bottle,Djang...

Python Web框架哪个好用?(python3 web框架)

  问:PythonWeb框架哪个好用?  答:  1.Django  Django是Python世界中最出名、最成熟的Web框架。Django功能全面,各模块之间结合紧密,(不讲其他的)Djang...

Vue3.0+Tornado6.1发布订阅模式打造异步非阻塞实时=通信聊天系统

“表达欲”是人类成长史上的强大“源动力”,恩格斯早就直截了当地指出,处在蒙昧时代即低级阶段的人类,“以果实、坚果、根作为食物;音节清晰的语言的产生是这一时期的主要成就”。而在网络时代人们的表达欲往往更...

Python开源项目合集(第三方平台)(python第三方开发工具)

wechat-python-sdk-wechat-python-sdk微信公众平台Python开发包http://wechat-python-sdk.readthedocs.org/,非官方...

IT界10倍高效学习法!用这种方式,一年学完清华大学四年的课程

有没有在某一个瞬间,让你放弃学编程刚开始学python时,我找了几十本国内外的python编程书籍学习后,我还是似懂非懂,那些书里面到处都是抽象的概念,复杂的逻辑,这样的书,对于专业开发者来说,在平常...

如何将Python算法模型注册成Spark UDF函数实现全景模型部署

背景Background对于算法业务团队来说,将训练好的模型部署成服务的业务场景是非常常见的。通常会应用于三个场景:部署到流式程序里,比如风控需要通过流式处理来实时监控。部署到批任务中部署成API服...

取消回复欢迎 发表评论: