controller层service中有许多if/else判断servlet路径然后调用相应的方法
目的:根据用户请求的url利用反射动态调用service方法,避免繁琐的if/else判断servletPath
public class UrlparttenUtil {
/**
* 通过urlpartten中最后一个'/'的索引 取出service方法名调用该方法
* @param clazz 类名.class
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
public static void get(Class clazz, HttpServletRequest request, HttpServletResponse response) {
String servletPath = request.getServletPath();
int index = servletPath.lastIndexOf("/") + 1;
String path = servletPath.substring(index);
System.out.println(servletPath+"---->method:"+path);
try {
Object obj = clazz.newInstance();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if(method.getName().equals(path)){
method.setAccessible(true);//设置为true可调用类的私有方法
method.invoke(obj, request,response);
}
}
} catch (IllegalAccessException | SecurityException | IllegalArgumentException
| InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
}
}