时隔多天 终于又有机会来继续完成第四篇文章 忙死了
本篇将会实现@RequestParam注解,以及简单的接口请求参数使用
这个注解主要是指定请求参数的名称
首先定义注解
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestParam {
String value() default "";//指定http参数名字
}
这个注解的属性 不再过多说明 与前面的注解区别就是这个注解是用在参数上的
我们的目的就是 在控制器当中的方法上绑定一个我们想要的参数 然后能够获取并操作它 所以我们先这样写
定义一个方法 参数名字叫“name”
然后我们需要通过注解来读到这个参数 并在激活这个testParam方法时候 能够正确传递参数
所以之前的handleRequest方法我们需要这么做
public Object handleRequest(String path, Map<String, String> params){
//根据fullPath获得方法
Method method=requestMappingMethods.get(path);
if (method!=null){
try {
Object Controller=beansMap.get(method.getDeclaringClass().getSimpleName());
Parameter[] parameters=method.getParameters();
Object[] args=new Object[parameters.length];
for (int i=0;i<parameters.length;i++){
Parameter parameter=parameters[i];
if (parameter.isAnnotationPresent(RequestParam.class)){
RequestParam requestParam=parameter.getAnnotation(RequestParam.class);
String paramName=requestParam.value().isEmpty()?parameter.getName():requestParam.value();
String paramValue=params.get(paramName);
args[i]=covertType(paramValue, parameter.getType());
}else {
args[i]=null;
}
}
return method.invoke(Controller, args);
}catch (Exception e){
System.out.println("出现错误");
}
}
return "404 not found";
}
解释:
获得方法 新增了args作为参数数组 参数数组长度为方法的参数数量(method.getParameters) 然后扫描带有RequestParam注解的方法 扫描到了以后 对每个parameter 获得注解的value并将参数数组给装填 然后coverType方法是转换参数类型并且检查参数
测试
成功解析参数 并且测试通过 实现了参数绑定~
后记
仓库地址(不断更新):
全系列:杜明珅的手搓spring迷你框架系列