一个servlet响应多个请求实现方式--反射

只需写一个servlet,作为一个中转站。
根据传来的参数className反射获取对应的类字节码,methodName反射获取对应的方法。然后调用。


@WebServlet("/CenterServlet")
public class CenterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String className = request.getParameter("className");
className = "com.wu.action."+className;
String methodName = request.getParameter("methodName");
Class clazz = null;
Method method = null;
//className=com.wu.action.LoginAction 这里的className要完整
clazz = Class.forName(className);//
method = clazz.getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
method.invoke(clazz,request, response);
//object is not an instance of declaring class说明未实例化,我们可以让反射的方法称为静态,就不要实例化了。
//method.invoke(request, response);wrong number of arguments
//对于静态的,只需传入clazz。method.invoke(clazz,request, response);
//或者也可以method.invoke(_class.newInstance(), args);
}
}
创建其他普通的java类
public class LoginAction {
public static void login(HttpServletRequest request, HttpServletResponse response){
PrintWriter out = response.getWriter();
out.write("LoginAction login");
System.out.println("LoginAction login");
}
public static void login1(HttpServletRequest request, HttpServletResponse response){
PrintWriter out = response.getWriter();
out.write("LoginAction login1");
System.out.println("LoginAction login1");
}
}

需要调用的时候:用参数指定类名 方法名
http://localhost:8080/OnlineOrder/CenterServlet?className=LoginAction&methodName=login1

为了写成实现以下这种url:用路径信息指定类名 方法名
http://localhost:8080/OnlineOrder/CenterServlet/
className /methodName?userName=wuyiming&password=123456

首先:
@WebServlet(“/CenterServlet”)
改成:@WebServlet(“/CenterServlet/*”)
这样就能匹配/CenterServlet/*的各种url。
调用request.getPathInfo()能获取 / className / methodName
通过截取pathInfo.substring(1,pathInfo.length()).split(“/”);
就可以获得className或methodName

String pathInfo = request.getPathInfo();
String[] classAndMethodName = pathInfo.substring(1,pathInfo.length()).split(“/”);
String className = “com.wu.action.”+classAndMethodName[0];
String methodName = classAndMethodName[1];

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值