1. 程式人生 > 其它 >Servlet之自定義請求處理方法並通過反射設定

Servlet之自定義請求處理方法並通過反射設定

簡介:

獲取瀏覽器傳送的引數,然後通過反射獲取接收引數的對應方法;

這樣通過反射進行方法的呼叫,當類中需要增加一個或多個方法時,就不需要做多個引數(方法名)的識別判斷,且不用將每一個方法都進行一次呼叫,只需要將獲取的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() --------"); } }

瀏覽器請求:

控制檯輸出:

這樣就通過傳入的引數(方法名稱)進行反射呼叫。