BaseServlet:
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri=request.getRequestURI();
String methodName=uri.substring(uri.lastIndexOf("/")+1);
//getMethod(methodName,Class...)
try {
//根据方法名,参数类型 获取方法对象
Method method=this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
// this:调用目标方法的对象 request,response 传入的参数
method.invoke(this,request,response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Servlet:
@WebServlet("/user/*") // /user/list /user/add /user/update....
public class UserServlet extends BaseServlet {
public void list(HttpServletRequest request, HttpServletResponse response) {
System.out.println("list...");
}
public void add(HttpServletRequest request, HttpServletResponse response) {
System.out.println("add...");
}
public void update(HttpServletRequest request, HttpServletResponse response) {
System.out.println("update...");
}
}