想用反射获取并执行本类的方法,从而减少servlet的数量, 则要反射方法的权限必须足够大;(doGet()权限为protected,要反射的queryAll()权限为public)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 获取客户端请求参数
* 反射调用相关方法
*
*/
try {
//获取页面传过来的operator参数
String operator = request.getParameter("operator");
//获得本类的class文件
Class clazz = this.getClass();
//反射获得方法并传参
Method method = clazz.getMethod(operator, HttpServletRequest.class, HttpServletResponse.class);
//执行方法并传参
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void queryAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
\\\\
}
原文:https://www.cnblogs.com/mryd/p/14175163.html