工具类--BaseServlet
工具类–BaseServlet
1、代码
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// localhost:8080/store/productServlet?method=addProduct
String method = req.getParameter("method");
if (null == method || "".equals(method) || method.trim().equals("")) {
method = "execute";
}
// 注意:此处的this代表的是子类的对象
// System.out.println(this);
// 子类对象字节码对象
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();
}
}
// 默认方法
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
return null;
}
2、逻辑
(1)获取请求参数method,确定具体需要执行的方法名
(2)获取当前运行类需要执行的方法Method
(3)执行当前运行类对应的方法
(4)通过方法返回值确定请求转发jsp位置
3、注意
(1)web.xml配置
(2)通过servlet转发给对应的实现类,输出进行测试