在MVC中使用转发地址栏不发生变化,而使用BaseController反射原理是,地址栏解析出来的方法名为转发之前的地址栏名称,所以在反射时出现java.lang.NoSuchMethodException异常。而使用重定向则地址栏发生变化。利用发射可以成功解析出方法名。c
protected void displayInterface(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String searchKeywords = req.getParameter("searchKeywords");
if (searchKeywords == null){
searchKeywords = "";
}
//查询全部书籍
//查询页码和每页显示大小
String pageNoStr = req.getParameter("pageNo");
String pageSizeStr = req.getParameter("pageSize");
int pageNo = 1;
if(pageNoStr != null){
pageNo = Integer.valueOf(pageNoStr);
}
int pageSize = 5;
if (pageSizeStr != null){
pageSize = Integer.valueOf(pageSizeStr);
}
Page page = bookService.queryBookByPage(pageNo, pageSize,searchKeywords);
page.setSearchKeywords("searchKeywords="+searchKeywords);
page.setQueryUrl("bookstore/displayInterface");
HttpSession session = req.getSession();
session.setAttribute("searchKeywords",searchKeywords);
session.setAttribute("PageInfo",page);
session.setAttribute("searchKeywords",searchKeywords);
// req.setAttribute("searchKeywords",searchKeywords);
// req.setAttribute("PageInfo",page);
// req.getRequestDispatcher("/displayInterface.jsp").forward(req,resp);
resp.sendRedirect("/displayInterface.jsp");
}
此例中,在最后代码区域,(注释代码)使用转发,地址栏为发生变化。通过BaseController来解析会产生java.lang.NoSuchMethodException异常。而使用重定向地址栏发生变化。则可以成功解析方法名。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI();
String[] split = requestURI.split("/");
String methodName = split[split.length - 1];
//使用 反射 通过方法名获取下面的方法
Class aClass = this.getClass();
try {
//获取方法
Method declaredMethod = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//暴力 破解方法的访问修饰符
declaredMethod.setAccessible(true);
//执行方法
declaredMethod.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}