自己动手写SpringMVC(七)

最后一个任务:任务五:实现doGet()  doPost()方法;代码中调用了hand()方法,基本原理和以前的差不多,因此不做详细说明!

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String uri = req.getRequestURI();
		String context = req.getContextPath();
		String path = uri.replace(context, "");		
		Method method =(Method) handlerMap.get(path);
		StudentController instance = (StudentController) beans.get("/"+path.split("/")[1]);
		Object arg[] = hand(req,resp,method);
		try {
			method.invoke(instance, arg);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	private static Object[] hand(HttpServletRequest request, HttpServletResponse response,Method method){
		//拿到当前待执行的方法有哪些参数
		Class<?>[] paramClazzs = method.getParameterTypes();
		Object[] args = new Object[paramClazzs.length];
		int args_i=0;
		int index = 0;
		for(Class<?> paramClazz:paramClazzs){
			if(ServletRequest.class.isAssignableFrom(paramClazz)){
				args[args_i++]=request;
			}
			if(ServletRequest.class.isAssignableFrom(paramClazz)){
				args[args_i++]=response;
			}
			Annotation[]  paramAns = method.getParameterAnnotations()[index];
			if(paramAns.length>0){
				for(Annotation paramAn:paramAns){
					if(MyRequestParam.class.isAssignableFrom(paramAn.getClass())){
						MyRequestParam rp = (MyRequestParam) paramAn;
						args[args_i++]=request.getParameter(rp.value());
					}
				}
			}
			index++;
		}
		return args;
	}

猜你喜欢

转载自blog.csdn.net/tangtang1226/article/details/81516363