一個servlet響應多個請求實現方式--反射
阿新 • • 發佈:2019-02-18
只需寫一個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");
}
}
為了寫成實現以下這種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];