BaseServlet的抽取其实就是将每个Servelt封装成为每一个模块功能到到一个类中.此类继承BaseServlet类,BaseServlet继承HttpServlet,再根据Servlet的生命周期,会执行service方法,所以在BaseServlet中重写service方法,再在service方法中通过反射去执行到每个具体的Servlet类中的每个模块功能,简化代码。
//这个抽象类,BaseServlet类不需要在web.xml中进行配置
public abstract class BaseServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//完成方法分发
//1.获取请求路径
String uri = req.getRequestURI();
//2.获取方法名称
String methodName = uri.substring(uri.lastIndexOf("/") + 1);
//1.1判断 参数是否为空 若为空,执行默认的方法
if(methodName == null || methodName .trim().length()==0){
methodName = "execute";
}
try {
// 2、通过反射获得当前运行类中指定方法,形式参数
Method executeMethod = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 3、反射执行方法
executeMethod.invoke(this, request, response);
} catch (NoSuchMethodException e) {
throw new RuntimeException("请求的方法[" + methodName + "]不存在");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("服务器异常", e);
}
}
/**
* 此方法用于复写,方便子类编程,默认执行方法
*/
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}