在開發中,對頁面的請求要創建對個servlet來進行處理,一個servlet只能處理一個請求,這樣要創建多個servlet,不利於開發和以後程序的維護,我們可以對同一個模塊進行合併創建一個servlet即可,比如登錄模塊,商品模塊,訂單模塊等等.只需要他們繼承BaseServlet,並在前臺頁面傳遞所調用的方法名即可.
package cn.itcast.stroe.utils;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1、獲取方法名
String methodName = request.getParameter("methodName");
//2、獲取當前運行類的class對象
Class clazz = this.getClass();
//3、動態獲取方法對象
if(methodName!=null&&!"".equals(methodName)){
try {
Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
//執行
String path = (String) method.invoke(this, request,response);
//判斷 是否需要請求轉發
if(path!=null&&!"".equals(path)){
//請求轉發
request.getRequestDispatcher(path).forward(request, response);
return;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.out.println("你需要的方法不存在");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}