通过反射提取功能模块的通用Servlet
通过继承HttpServlet(该类即为模板类),重写service方法(在service通过反射获得相应的方法,执行,并跳转到相应的页面),其他功能模块的Servlet类继承该类,并提供相应的方法,方法可返回要跳转的页面路径。
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// localhost:8080/store/productServlet?method=addProduct
//获取客户端提交到服务端的method对应的值
String method = req.getParameter("method");
if (null == method || "".equals(method) || method.trim().equals("")) {
method = "execute";
}
// 注意:此处的this代表的是子类的对象
// System.out.println(this);
//获取到当前字节码对象(ServletDemo03.class在内存中对象)
// 子类对象字节码对象
Class clazz = this.getClass();
try {
// 查找子类对象对应的字节码中的名称为method的方法.这个方法的参数类型是:HttpServletRequest.class,HttpServletResponse.class
Method md = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
if(null!=md){
//定义变量,存放功能执行完毕之后要转发的路径
String jspPath = (String) md.invoke(this, req, resp);
if (null != jspPath) {
req.getRequestDispatcher(jspPath).forward(req, resp);//服务端的转发
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 默认方法,该方法用于当传递的method参数在子类查不到相应的方法时调用
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
return null;
}
}
public class ServletDemo03 extends BaseServlet {
public ServletDemo03() {
System.out.println("么有参数构造函数");
}
public String addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("添加学生");
return "/test.html";
}
public String delStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("删除学生");
return "/test.html";
}
public String checkStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("检查学生");
response.getWriter().println("DDDDDD");
return null;
}
}