public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取传递过来的method
String methodName = request.getParameter("method");
//跳转路径
String path = null;
//如果method为null,则赋值execute
if(StringUtils.isBlank(methodName)){
methodName = "execute";
}
//反射获取方法
Class<? extends BaseServlet> clazz = this.getClass();
try {
Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
//执行方法,返回要跳转的url 这边要约定方法要返回String
path = (String) method.invoke(this, request,response);
//跳转
if(null != path){
request.getRequestDispatcher(path).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//客户端没有传递 method 默认执行的方法
public String execute (HttpServletRequest request, HttpServletResponse response) throws Exception {
return null;
}
}