Loading

servlet的抽取

  1. 在调用接口的时候传递参数,然后接收这个参数
  2. 将这个参数作为方法名 利用反射技术调用该方法
public class BaseServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			String methodName=req.getParameter("method");
			Class clazz=this.getClass();//this代表所访问的类的对象,
			Method method=clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(clazz.newInstance(), req,resp);
		} catch (Exception e) {		
			e.printStackTrace();
		} 
		
		
	}
}

完成这个BaseServlet之后,以后写servlet可以直接继承这个类

posted @ 2021-03-26 12:17  克豪  阅读(65)  评论(0)    收藏  举报