12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package cn.nosum.framework.mvc.v4.servlet;
- import cn.nosum.framework.annotation.RequestParam;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.lang.annotation.Annotation;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.Map;
- public class HandlerAdapter {
- public ModelAndView handler(HttpServletRequest req, HttpServletResponse resp, HandlerMapping handler) throws Exception{
- // 保存参数名称和参数的位置
- Map<String,Integer> paramIndexMapping = new HashMap<String, Integer>();
- // 通过运行时的状态取得方法参数的 annotation
- Annotation[] [] pa = handler.getMethod().getParameterAnnotations();
- for (int i = 0; i < pa.length ; i ++) {
- for(Annotation a : pa[i]){
- if(a instanceof RequestParam){
- String paramName = ((RequestParam) a).value();
- if(!"".equals(paramName.trim())){
- paramIndexMapping.put(paramName,i);
- }
- }
- }
- }
- // 初始化
- Class<?> [] paramTypes = handler.getMethod().getParameterTypes();
- for (int i = 0; i < paramTypes.length; i++) {
- Class<?> paramterType = paramTypes[i];
- if(paramterType == HttpServletRequest.class || paramterType == HttpServletResponse.class){
- paramIndexMapping.put(paramterType.getName(),i);
- }
- }
- // 拼接实参列表
- Map<String,String[]> params = req.getParameterMap();
- Object [] paramValues = new Object[paramTypes.length];
- for (Map.Entry<String,String[]> param : params.entrySet()) {
- String value = Arrays.toString(params.get(param.getKey()))
- .replaceAll("\\[|\\]","")
- .replaceAll("\\s+",",");
- if(!paramIndexMapping.containsKey(param.getKey())){continue;}
- int index = paramIndexMapping.get(param.getKey());
- // 允许自定义的类型转换器Converter
- paramValues[index] = castStringValue(value,paramTypes[index]);
- }
- if(paramIndexMapping.containsKey(HttpServletRequest.class.getName())){
- int index = paramIndexMapping.get(HttpServletRequest.class.getName());
- paramValues[index] = req;
- }
- if(paramIndexMapping.containsKey(HttpServletResponse.class.getName())){
- int index = paramIndexMapping.get(HttpServletResponse.class.getName());
- paramValues[index] = resp;
- }
- Object result = handler.getMethod().invoke(handler.getController(),paramValues);
- if(result == null || result instanceof Void){return null;}
- boolean isModelAndView = handler.getMethod().getReturnType() == ModelAndView.class;
- if(isModelAndView){
- return (ModelAndView)result;
- }
- return null;
- }
- private Object castStringValue(String value, Class<?> paramType) {
- if(String.class == paramType){
- return value;
- }else if(Integer.class == paramType){
- return Integer.valueOf(value);
- }else if(Double.class == paramType){
- return Double.valueOf(value);
- }else {
- if(value != null){
- return value;
- }
- return null;
- }
- }
- }
|