2.6完善反射的代码
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 假设url是: http://localhost:8080/mymvc/hello.do // ServletPath是Servlet的访问路径: /hello.do // 思路是: // 第1步: /hello.do -> hello // 第2步: hello -> HelloController String servletPath = request.getServletPath(); // /hello.do int lastDotIndex = servletPath.lastIndexOf(".do"); servletPath = servletPath.substring(1, lastDotIndex); // hello // 通过ServletPath获取对应的Controller对象 Object xxxController = map.get(servletPath); String ac = request.getParameter("ac"); System.out.println("=======" + ac + "======"); if (StringUtil.isEmpty(ac)) ac = "index"; try { // 这里只能try...catch异常,因为在重写的方法里,不能抛出比父类更大的异常 Method method = xxxController.getClass().getDeclaredMethod(ac, HttpServletRequest.class, HttpServletResponse.class); if (method != null) { method.invoke(xxxController, request, response); } else { throw new RuntimeException("ac值错误"); } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } }