1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
| public class SWDispatcherServlet extends HttpServlet {
private Properties properties = new Properties();
private List<String> classNames = new ArrayList<>();
private Map<String, Object> ioc = new HashMap<>();
private Map<String, Method> handlerMapping = new HashMap<>();
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doDispatch(req,resp);
}
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { doDispatch(req,resp);
}
@Override public void init(ServletConfig config) { doLoadConfig(config.getInitParameter("contextConfigLocation"));
doScanner(properties.getProperty("scanPackage"));
doInstance();
doAutowired();
initHandlerMapping();
System.out.println("初始化成功"); }
private void doLoadConfig(String location) {
InputStream inputStream =null; try { inputStream = this.getClass().getClassLoader().getResourceAsStream(location); properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != inputStream) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
private void doScanner(String packageName) { URL url = this.getClass().getClassLoader() .getResource("/" + packageName.replaceAll("\\.", "/")); File classDir = new File(Objects.requireNonNull(url).getFile()); for(File file : Objects.requireNonNull(classDir.listFiles())){
if(file.isDirectory()){ doScanner(packageName + "." + file.getName()); }else { String className = packageName + "." + file.getName().replace(".class","").trim(); classNames.add(className); } }
}
private void doInstance() { if(classNames.isEmpty()){ return; } for(String className : classNames){ try { Class<?> clazz = Class.forName(className);
if(clazz.isAnnotationPresent(SWController.class)){ String beanName = toLowStr(clazz.getSimpleName()); ioc.put(beanName, clazz.newInstance()); }else if(clazz.isAnnotationPresent(SWService.class)){ SWService swService = clazz.getAnnotation(SWService.class); String beanName = swService.value(); if(!"".equals(beanName.trim())){ ioc.put(beanName, clazz.newInstance()); continue; }
Class<?>[] interfaces = clazz.getInterfaces(); for(Class<?> i : interfaces){ ioc.put(i.getName(), clazz.newInstance()); } } } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); }
} }
private void doAutowired() { if(ioc.isEmpty()){ return; }
for (Map.Entry<String, Object> entry : ioc.entrySet()){ Field[] fields = entry.getValue().getClass().getDeclaredFields();
for(Field field : fields){ if(!field.isAnnotationPresent(SWAutowried.class)){ continue; }
SWAutowried swAutowried = field.getAnnotation(SWAutowried.class);
String beanName = swAutowried.value().trim(); if("".equals(beanName)){ beanName = field.getType().getName(); }
field.setAccessible(true);
try { field.set(entry.getValue(), ioc.get(beanName)); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
}
private void initHandlerMapping() { if(!ioc.isEmpty()){ for(Map.Entry<String, Object> entry : ioc.entrySet()){ Class<?> clazz = entry.getValue().getClass(); if(!clazz.isAnnotationPresent(SWController.class)){ continue; } String url = ""; if(clazz.isAnnotationPresent(SWRequestMapping.class)){ SWRequestMapping swRequestMapping = clazz.getAnnotation(SWRequestMapping.class); url = swRequestMapping.value(); } Method[] methods = clazz.getMethods(); for(Method method : methods){ if(!method.isAnnotationPresent(SWRequestMapping.class)){ continue; } SWRequestMapping swRequestMapping = method.getAnnotation(SWRequestMapping.class); String mUrl = url + swRequestMapping.value(); handlerMapping.put(mUrl, method); System.out.println("Mapping : " + mUrl + " " + method); }
} } }
private void doDispatch(HttpServletRequest request, HttpServletResponse response) { String url = request.getRequestURI(); String contextPath = request.getContextPath(); url = url.replace(contextPath, "").replaceAll("/+", "/"); if(!handlerMapping.containsKey(url)){ try { response.getWriter().write("404"); return; } catch (IOException e) { e.printStackTrace(); } } Method method = handlerMapping.get(url); System.out.println("获得对应的方法" + method);
Class<?>[] parameterTypes = method.getParameterTypes(); Map<String, String[]> parameterMap = request.getParameterMap();
Object[] paramValues = new Object[parameterTypes.length]; for(int i = 0; i < parameterTypes.length; i++){ Class parameterType = parameterTypes[i]; if(parameterType == HttpServletRequest.class){ paramValues[i] = request; continue; }else if(parameterType == HttpServletResponse.class){ paramValues[i] = response; }else if(parameterType == String.class){ for(Map.Entry<String, String[]> entry : parameterMap.entrySet()){ String value = Arrays.toString(entry.getValue()).replaceAll("\\[|\\]","") .replaceAll(",\\s", ","); paramValues[i++] = value; if(i == parameterTypes.length){ break; } } } } try{ String beanName = toLowStr(method.getDeclaringClass().getSimpleName()); method.invoke(this.ioc.get(beanName), paramValues); }catch (Exception e){ e.printStackTrace(); } }
private String toLowStr(String str){ char[] ch = str.toCharArray(); ch[0] += 32; return String.valueOf(ch); } }
|