JavaWeb——通过反射提取功能模块的通用Servlet

本文介绍了一种通过反射机制实现的通用Servlet基类,该基类允许动态调用子类中的不同方法,从而实现灵活的功能模块化。通过继承HttpServlet并重写service方法,子类可以提供特定的方法来处理不同的请求,如添加、删除和检查学生信息。

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

通过反射提取功能模块的通用Servlet

通过继承HttpServlet(该类即为模板类),重写service方法(在service通过反射获得相应的方法,执行,并跳转到相应的页面),其他功能模块的Servlet类继承该类,并提供相应的方法,方法可返回要跳转的页面路径。

在这里插入图片描述

public class BaseServlet extends HttpServlet {
	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// localhost:8080/store/productServlet?method=addProduct
		//获取客户端提交到服务端的method对应的值
		String method = req.getParameter("method");

		if (null == method || "".equals(method) || method.trim().equals("")) {
			method = "execute";
		}

		// 注意:此处的this代表的是子类的对象
		// System.out.println(this);
		//获取到当前字节码对象(ServletDemo03.class在内存中对象)
		// 子类对象字节码对象
		Class clazz = this.getClass();

		try {
			// 查找子类对象对应的字节码中的名称为method的方法.这个方法的参数类型是:HttpServletRequest.class,HttpServletResponse.class
			Method md = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
			if(null!=md){
			    //定义变量,存放功能执行完毕之后要转发的路径
				String jspPath = (String) md.invoke(this, req, resp);
				if (null != jspPath) {
					req.getRequestDispatcher(jspPath).forward(req, resp);//服务端的转发
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 默认方法,该方法用于当传递的method参数在子类查不到相应的方法时调用
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		return null;
	}

}
public class ServletDemo03 extends BaseServlet {
	public ServletDemo03() {
		System.out.println("么有参数构造函数");
	}
	
	public String addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("添加学生");
		return "/test.html";
		
	}
	public String delStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("删除学生");
		return "/test.html";
		
	}
	public String checkStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("检查学生");
		response.getWriter().println("DDDDDD");
		return null;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值