在进行项目开发时,有时候用户的一个操作就会新增一个Servlet来处理相应的操作,造成Sevlet的冗余现象
为了解决Servlet太多的造成冗余的现象,我们只需定义一个BaseServlet来获取用户想要调用的方法名,通过方法的名称反射来调用该类的其他方法。这样原来定义的很多个Servlet就不再需要了。
步骤1:定义一个抽象类BaseServlet和自定义的Servlet来继承BaseServlet。自定义的Servlet就会有父类的所有方法(注意Servlet的三个生命周期方法 当调用了某个Servlet,其中的init() servlet(rqs,rep),destory()都会自动调用。
步骤2:获取用户传入参数中方法名称,通过反射的方法来获取到该类,通过反射方法来调用自定义类的方法,执行该方法即可
public abstract class BaseServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取参数,用来识别用户想请求的方法
* 2. 然后判断是否哪一个方法,是哪一个我们就调用哪一个
*/
String methodName = req.getParameter("method");
if(methodName == null || methodName.trim().isEmpty()) {
throw new RuntimeException("您没有传递method参数!无法确定您想要调用的方法!");
}
/*
* 1. 得到方法名,通过方法名再得到Method类的对象!
* * 需要得到Class,然后调用它的方法进行查询!得到Method
* * 我们要查询的是当前类的方法,所以我们需要得到当前类的Class
*/
Class c = this.getClass();//得到当前类的class对象
Method method = null;
try {
method = c.getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法:" + methodName + "(HttpServletRequest,HttpServletResponse),它不存在!");
}
/*
* 调用method表示的方法
*/
try {
String result = (String)method.invoke(this, req, resp);
} catch (Exception e) {
System.out.println("您调用的方法:" + methodName + ", 它内部抛出了异常!");
throw new RuntimeException(e);
}
}
}
自定义的Servlet继承BaseServlet会自动调用Service方法,来判断传入的参数进而调用对应的方法
public class BServlet extends BaseServlet {
public void fun1(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("fun1()...");
}
public void fun2(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("fun2()...");
}
public void fun3(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("fun3()...");
}
}