文章目录
- 1.将方法的request和response参数封装到参数数组
- 1.SunDispatcherServlet.java
-
- 2.测试
- 2.封装Http请求参数到参数数组
- 1.自定义@RequestParam注解
- 2.MonsterController.java 增加参数
- 3.SunDispatcherServlet.java
- 1.resolveMethodArguments 根据方法信息,返回实参列表
- 2.测试
1.将方法的request和response参数封装到参数数组
1.SunDispatcherServlet.java
1.根据方法信息,返回实参列表
private Object[] resolveMethodArguments(HttpServletRequest request, HttpServletResponse response, Method method) {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> parameterType = parameterTypes[i];
if (parameterType == HttpServletRequest.class) {
args[i] = request;
} else if (parameterType == HttpServletResponse.class) {
args[i] = response;
} else {
}
}
return args;
}
2.具体调用
2.测试
2.封装Http请求参数到参数数组
1.自定义@RequestParam注解
package com.sunxiansheng.springmvc.annotation;
import java.lang.annotation.*;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.PARAMETER)
@Documented
public @interface RequestParam {
String name() default "";
}
2.MonsterController.java 增加参数
3.SunDispatcherServlet.java
1.resolveMethodArguments 根据方法信息,返回实参列表
private Object[] resolveMethodArguments(HttpServletRequest request, HttpServletResponse response, Method method) {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> parameterType = parameterTypes[i];
if (parameterType == HttpServletRequest.class) {
args[i] = request;
} else if (parameterType == HttpServletResponse.class) {
args[i] = response;
} else {
if (method.getParameters()[i].isAnnotationPresent(RequestParam.class)) {
String parameterName = method.getParameters()[i].getAnnotation(RequestParam.class).name();
String parameter = request.getParameter(parameterName);
args[i] = parameter;
} else {
String parameterName = method.getParameters()[i].getName();
String parameter = request.getParameter(parameterName);
if (parameter == null || parameter.isEmpty()) {
log.error("参数名匹配失败:{}", parameter);
}
args[i] = parameter;
}
}
}
int count = 0;
for (Object arg : args) {
if (arg != null) {
count++;
}
}
if (count != parameterTypes.length) {
throw new RuntimeException("参数个数不匹配");
}
return args;
}
2.测试