JavaEE之BaseServlet的抽取

本文介绍了一种通过BaseServlet类泛化实现不同业务Servlet的方法,利用反射机制动态调用相应的方法,简化了传统条件判断语句,提高了代码的可维护性和复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BaseServlet

如何抽取各个业务的Servlet?

    通过反射得到指定方法名的方法对象,且调用方法。

此处this表示该方法所在的对象

Method method = this.getClass().getDeclaredMethod(String name,Class<?> parameterTypes); 

参数1:方法的名字

参数2:参数的类型

method.invoke(Object obj,Object... args);

参数1:该方法所在对象

参数2:参数

/**
 * 具体业务的基类(通用代码)
 * @author chenzuyi
 *
 */
public class BaseServlet extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 以下这段代码的共性:
		// 1)接收到action的参数 2)根据不同的参数值调用不同的方法(约定前提:方法名和action的参数值一致的!!!)
		/**
		 * 用户访问的URL: 增加: /contact?action=addCon 修改: /contact?action=updCon 删除:
		 * /contact?action=delCon 查询: /contact?action=listCon
		 */
		// 1)获取action的参数值
		String action = request.getParameter("action");
		// 2)根据action参数值决定执行什么功能
		/*
		 * if(action.equals("addCon")){ addCon(request, response); }else
		 * if(action.equals("updCon")){ updCon(request, response); }else
		 * if(action.equals("listCon")){ listCon(request, response); }
		 */
		try {
			/**
			 * 通过反射得到指定方法名的方法对象,且调用方法
			 */
			Method method = this.getClass().getDeclaredMethod(action,
					HttpServletRequest.class, HttpServletResponse.class);
			// 执行方法
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值