自己动手写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;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值