zoukankan      html  css  js  c++  java
  • 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  " 

  • 相关阅读:
    GoogleMaps 之创意应用——数码照片定位
    SGI面临破产
    Google地图搜索的触角伸向月球
    说“丛林法则”
    比Google Map更加清晰的网络地图——RealBird
    Office 12眩酷界面,先睹为快
    Paypal将正式登陆中国——贝宝
    地图技术的领导者RealBird与Google Maps的无缝结合
    微软欲封杀OpenGL?
    网络地图服务究竟商机何在?
  • 原文地址:https://www.cnblogs.com/iamkk/p/6131304.html
Copyright © 2011-2022 走看看