利用java反射機制實現javaweb自動呼叫類的方法
阿新 • • 發佈:2019-02-06
public class BookServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } //建立BookService物件 private BookService bookService = new BookService(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*利用java反射機制實現自動呼叫類的方法 : * 聲明後利用反射,當JSP等介面給出連結 bookServlet?method=''時呼叫bookServlet相應的方法 比如:books.JSP介面的 <a href="bookServlet?method=getBooks">呼叫相應的getBooks()方法*/ //1.request呼叫宣告methodName獲取方法名 String methodName = request.getParameter("method"); try { //2.獲取該類所需求的方法(非公共許可權) Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); //3.設定非公共許可權方法可呼叫 method.setAccessible(true); //4.invoke呼叫反射方法的實現 method.invoke(this, request, response); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } //獲取圖書資訊 protected void getBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageNoStr = request.getParameter("pageNo"); String minPriceStr = request.getParameter("minPrice"); String maxPriceStr = request.getParameter("maxPrice"); int pageNo = 1; int minPrice= 0; int maxPrice = Integer.MAX_VALUE; //request.getParameter返回值是String,需要進行強制型別轉換為int型別 try { pageNo = Integer.parseInt(pageNoStr); } catch (NumberFormatException e) {} try { minPrice = Integer.parseInt(minPriceStr); } catch (NumberFormatException e) {} try { maxPrice = Integer.parseInt(maxPriceStr); } catch (NumberFormatException e) {} //初始化構造器傳參建立封裝條件的CriteriaBook物件 CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo); //傳參CriteriaBook物件 ,呼叫上面建立的bookService物件獲取page物件的方法例項化page物件 Page<Book> page = bookService.getPage(criteriaBook); //設定page物件進行賦值 request.setAttribute("bookpage", page); //轉發資料到books介面 request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response); } }