JSP+Servlet的请求处理方法的指定

版权声明:开源交流,可以不进行特殊介绍,但请尊重个人劳动成果,互相交流哦! https://blog.csdn.net/wanglizheng825034277/article/details/45650155
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的(不然仍然使用第一种方法会报没有改方法的异常)。

猜你喜欢

转载自blog.csdn.net/wanglizheng825034277/article/details/45650155