反射實現定位Servlet中的方法
阿新 • • 發佈:2018-11-05
public class BaseServlet extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設定編碼表 req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); // 接收引數: String methodName = req.getParameter("method"); //如果method傳遞的引數為null或者為空字串,作出提示 if(methodName == null || "".equals(methodName)){ resp.getWriter().println("method引數為null!!!"); return; } // 獲得子類的Class物件: /** * this.class代表載入繼承了這個BaseServlet的class物件 * */ Class clazz = this.getClass(); // 獲得子類中的方法了: try { Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); // 使方法執行,並獲取子類return的字串 String path = (String)method.invoke(this, req,resp); //轉發 if(path != null){ req.getRequestDispatcher(path).forward(req, resp); } } catch (Exception e) { e.printStackTrace(); } } }