BaseServlet存在的意义和基本的原理

在进行项目开发时,有时候用户的一个操作就会新增一个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()...");
	}
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值