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

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

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

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

相关推荐

2025南通中考作文解读之四:结构框架

文题《继续走,迈向远方》结构框架:清晰叙事,层层递进示例结构:1.开头(点题):用环境描写或比喻引出“走”与“远方”,如“人生如一条长路,每一次驻足后,都需要继续走,才能看见更美的风景”。2.中间...

高中数学的知识框架(高中数学知识框架图第三章)

高中数学的知识框架可以划分为多个核心板块,每个板块包含具体的知识点与内容,以下为详细的知识框架结构:基础知识1.集合与逻辑用语:涵盖集合的概念、表示方式、性质、运算,以及命题、四种命题关系、充分条件...

决定人生的六大框架(决定人生的要素)

45岁的自己混到今天,其实是失败的,要是早点意识到影响人生的六大框架,也不至于今天的模样啊!排第一的是环境,不是有句话叫人是环境的产物,身边的环境包括身边的人和事,这些都会对一个人产生深远的影响。其次...

2023年想考过一级造价师土建计量,看这30个知识点(三)

第二章工程构造考点一:工业建筑分类[考频分析]★★★1.按厂房层数分:(1)单层厂房;(2)多层厂房;(3)混合层数厂房。2.按工业建筑用途分:(1)生产厂房;(2)生产辅助厂房;(3)动力用厂房;(...

一级建造师习题集-建筑工程实务(第一章-第二节-2)

建筑工程管理与实务题库(章节练习)第一章建筑工程技术第二节结构设计与构造二、结构设计1.常见建筑结构体系中,适用建筑高度最小的是()。A.框架结构体系B.剪力墙结构体系C.框架-剪力墙结构体系D...

冷眼读书丨多塔斜拉桥,这么美又这么牛

”重大交通基础设施的建设是国民经济和社会发展的先导,是交通运输行业新技术集中应用与创新的综合体现。多塔斜拉桥因跨越能力强、地形适应性强、造型优美等特点,备受桥梁设计者的青睐,在未来跨越海峡工程中将得...

2021一级造价师土建计量知识点:民用建筑分类

2021造价考试备考开始了,学霸君为大家整理了一级造价师备考所用的知识点,希望对大家的备考道路上有所帮助。  民用建筑分类  一、按层数和高度分  1.住宅建筑按层数分类:1~3层为低层住宅,4~6层...

6个建筑结构常见类型,你都知道吗?

建筑结构是建筑物中支承荷载(作用)起骨架作用的体系。结构是由构件组成的。构件有拉(压)杆、梁、板、柱、拱、壳、薄膜、索、基础等。常见的建筑结构类型有6种:砖混结构、砖木结构、框架结构、钢筋混凝土结构、...

框架结构设计经验总结(框架结构设计应注意哪些问题)

1.结构设计说明主要是设计依据,抗震等级,人防等级,地基情况及承载力,防潮抗渗做法,活荷载值,材料等级,施工中的注意事项,选用详图,通用详图或节点,以及在施工图中未画出而通过说明来表达的信息。2.各...

浅谈混凝土框架结构设计(混凝土框架结构设计主要内容)

浅谈混凝土框架结构设计 摘要:结构设计是个系统的全面的工作,需要扎实的理论知识功底,灵活创新的思维和严肃认真负责的工作态度。钢筋混凝土框架结构虽然相对简单,但设计中仍有很多需要注意的问题。本文针...

2022一级建造师《建筑实务》1A412020 结构设计 精细考点整理

历年真题分布统计1A412021常用建筑结构体系和应用一、混合结构体系【2012-3】指楼盖和屋盖采用钢筋混凝土或钢木结构,而墙和柱采用砌体结构建造的房屋,大多用在住宅、办公楼、教学楼建筑中。优点:...

破土动工!这个故宫“分院”科技含量有点儿高

故宫“分院”设计图。受访者供图近日,位于北京海淀区西北旺镇的故宫北院区项目已开始破土动工,该项目也被称作故宫“分院”,筹备近十年之久。据悉,故宫本院每年展览文物的数量不到1万件,但是“分院”建成后,预...

装配式结构体系介绍(上)(装配式结构如何设计)

PC构件深化、构件之间连接节点做法等与相应装配式结构体系密切相关。本节列举目前常见的几种装配式结构体系:装配整体式混凝土剪力墙结构体系、装配整体式混凝土框架结构体系、装配整体式混凝土空腔结构体系(S...

这些不是双向抗侧结构体系(这些不是双向抗侧结构体系的特点)

双向抗侧土木吧规范对双向抗恻力结构有何规定?为何不应采用单向有墙的结构?双向抗侧土木吧1.规范对双向抗侧力结构体系的要求抗侧力体系是指抵抗水平地震作用及风荷载的结构体系。对于结构体系的布置,规范针对...

2022一级建造师《建筑实务》1A412020 结构设计 精细化考点整理

1A412021常用建筑结构体系和应用一、混合结构体系【2012-3】指楼盖和屋盖采用钢筋混凝土或钢木结构,而墙和柱采用砌体结构建造的房屋,大多用在住宅、办公楼、教学楼建筑中。优点:抗压强度高,造价...

取消回复欢迎 发表评论: