1. 程式人生 > >JSP+Servlet的請求處理方法的指定

JSP+Servlet的請求處理方法的指定

1、在JSP介面中的請求中新增一個標記方法的屬性method
2、新建一個對應請求的servlet類,並新增doGet和doPost方法,並使用其中之一作為主要方法來使用呼叫
3、在作為主要方法的之一中的關鍵程式碼:
第一種:
String methodName = request.getAttribute("method");
Method method = getClass().getMethod(methodName,HttpRequest.class,HttpResponse.class);
method.invoke(this,request,response); // 第一個引數在api中代表操作建立的底層方法的物件,這裡是當前物件,所以為this
第二種:
String methodName = request.getAttribute("method");
Method method = getClass().getDeclareMethod(methodName,HttpRequest.class,HttpResponse.class);
method.setAccessible(true);
method.invoke(this,request,response);
注:第一種方法適用於在doGet和doPost方法外建立的方法名為methodName的方法的許可權為public,而第二種適用於建立的方法為保護的protected和private的(不然仍然使用第一種方法會報沒有改方法的異常)。