@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String action=req.getParameter("action");
try {
// 获取 action 业务鉴别字符串,获取相应的业务方法反射对象
//返回此Class对象所表示的类或接口的指定方法
Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
// 调用目标业务 方法
method.invoke(this,req,resp);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);//把异常抛给 Filter 过滤器
}
}
- 注:
getDeclaredMethod() 获取的是类自身声明的所有方法,包含public、protected和private方法。
getMethod () 获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。