项目_1.3_手写SpringMVC框架
初步修改项目

package com.hy.servlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hy.utils.StringUtil; @WebServlet("/cs") public class CoreServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ac = request.getParameter("ac"); System.out.println("======="+ac+"======"); if (StringUtil.isEmpty(ac)) ac = "index"; // 获取当前类的所有方法 Method[] methods = this.getClass().getDeclaredMethods(); for (Method m : methods) { // 获取方法名称 String methodName = m.getName(); if (ac.equals(methodName)) { // 找到和ac同名的方法,那么通过反射技术调用它 try { m.invoke(this, request, response); return; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } throw new RuntimeException("ac值错误"); } private void index(HttpServletRequest request, HttpServletResponse response) { System.out.println("aaaaaaaaaaa"); } }
package com.hy.utils; public class StringUtil { //判断字符串是否为null或者"" public static boolean isEmpty(String str){ return str==null || "".equals(str); } public static boolean isNotEmpty(String str){ return !isEmpty(str); } }

成功

浙公网安备 33010602011771号