简介:
获取浏览器发送的参数,然后通过反射获取接收参数的对应方法;
这样通过反射进行方法的调用,当类中需要增加一个或多个方法时,就不需要做多个参数(方法名)的识别判断,且不用将每一个方法都进行一次调用,只需要将获取的Method使用invoke()调用即可,大大地减少了重复操作。
代码:
package demo1;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 在这里给出多个请求处理方法 请求处理方法:除了名称以外,都与service方法相同
*
* @author CDU_LM
*
*/
@WebServlet("/AServlet")
public class AServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* 获取参数识别用户想要求情的方法 然后判断并调用对应的方法
*/
String methodName = req.getParameter("methodName");
if (methodName == null || methodName.trim().isEmpty()) {
throw new RuntimeException("没有传递参数");
}// 获取当前类class对象
Class<? extends AServlet> clazz = this.getClass();
// 设置接收方法的参数
Method method = null;
try {
// 获取对应方法,传入方法名和参数类型的class
method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("调用 " + methodName + " 方法不存在!!");
}
// 调用方法
try {
// 调用invoke()执行方法,
method.invoke(this, req, resp);
} catch (Exception e) {
System.out.println("调用" + methodName + "方法失败!!");
throw new RuntimeException(e);
}
}
public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("-------- addUser() --------");
resp.getWriter().print("-------- addUser() --------");
}
public void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("-------- modifyUser() --------");
resp.getWriter().print("-------- modifyUser() --------");
}
public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("-------- deleteUser() --------");
resp.getWriter().print("-------- deleteUser() --------");
}
}
浏览器请求:
控制台输出:
这样就通过传入的参数(方法名称)进行反射调用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)