一个Servlet中可以有多个处理请求的方法

BaseServlet

  一个请求写一个Servlet太过复杂和麻烦,我们希望在一个Servlet中可以有多个处理请求的方法。

  客户端发送请求时,必须给出一个参数,用来说明要调用的方法

  方法的结构和service()方法的结构一样

初始版

  当我们访问Servlet时,发生了那些操作?

  首先是通过<url-pattern>找到<servlet-name>,通过<serlvet-name>最终找到<servlet-class>,也就是类名,在通过反射得到Serlvet对象。

  再由tomcat调用init()、service()、destroy()方法,这一过程是Servlet的生命周期。在HttpServlet里有个service()的重载方法。ServletRequest、ServletResponse经过service(ServletRequest req,ServletResponse resp)方法转换成Http格式的。再在service(HttpServletRequest req,HttpServletResponse resp)中调用doGet()或者doPost()方法。

  路径:http://localhost:8080/baseservlet/base?method=addUser

public class BaseServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");//获取要调用的方法,其中的value="method"是自己约定的
		if("addUser".equals(method)){
			addUser(req,resp);
		}
		if("deleteUser".equals(method)){
			deleteUser();
		}
	}

	private void deleteUser() {
		System.out.println("deleteUser()");
	}

	private void addUser(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("add()");
		
	}
	
}

 改进版

  很显然,上面的代码不是我们想要的。

public class BaseServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("method");//获取方法名
		if(name == null || name.isEmpty()){
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method =  c.getMethod(name, HttpServletRequest.class,HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到"+name+"方法,请检查该方法是否存在");
		}
		
		try {
			method.invoke(this, req,resp);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法"+name+",内部发生了异常");
			throw new RuntimeException(e);
		}
		
	}
}

在项目中,用一个Servlet继承该BaseServlet就可以实现多个请求处理。  

部分资料来源网络

原文地址:https://www.cnblogs.com/ckui/p/6002029.html