只需写一个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];