java web(六)多个请求对应一个Servlet

概要:

  提交请求的常用方式有两种,get/post , 运行程序后被请求,在加载执行web.xml文件时通过该文件中的映射关系找到即将要执行的Servlet; 而在要执行的Servlet文件中可通过反射的方式找到要执行的方法,部分代码如下:

web.xml

  <servlet>
    <servlet-name>CustomerServlet</servlet-name>
    <servlet-class>com.kk.servlet.CustomerServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CustomerServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  ---提交的请求都要以 ".do" 结尾 

CustomerServlet.java

doPost方法体中:

  //1、获取ServletPath: /edit.do或 addCustomer.do
  String servletPath=request.getServletPath();
  //2、去除 / 和 .do ,得到类似于edit或addCustomer这样的字符串
  String methodName=servletPath.substring(1);
  methodName=methodName.substring(0, methodName.length()-3);
  System.out.println("所获取的值:"+servletPath+" 得到方法名 "+methodName);
  
  try {
   //3、利用反射获取menthodName获取对应的的方法 
   Method method=getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
   //利用反射调用methodName对应的方法
   method.invoke(this, request,response);
  } catch (Exception e) {
   response.sendRedirect("error.jsp");
  }

eg.

private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ..........................

}

以该方法为例,请求==>" delete.do  " 

原文地址:https://www.cnblogs.com/iamkk/p/6131304.html