你的位置:首页 > Java教程

[Java教程]java 反射机制 Demo 练习


最近在研究java 反射机制,看网上视频,并抄了下来研究,用到Servlet 注解,绝不亚于SpringMVC 的注解使用,特此记录分享,Servlet 再也不用为传递参数而判断担忧了,专注业务!

1. 首先定义一个父类,所有的业务操作全部继承之.

 1 package controller; 2  3 import java.io.IOException; 4 import java.lang.reflect.Method; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 @SuppressWarnings("serial")12 public abstract class DispatcherServlet extends HttpServlet {13 14   @Override15   public void init() throws ServletException {16   }17 18   @Override19   public void doGet(HttpServletRequest request, HttpServletResponse response)20       throws ServletException, IOException {21     String requestURI = request.getRequestURI();22     String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);23     String xpath = "/WEB-INF/view/errors.jsp";24     // 根据指定的方法名称反射调用指定的方法26     try {27       Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);28       // 反射调用方法29       xpath = (String) method.invoke(this, request, response);30     } catch (Exception e) {31     }32    request.getRequestDispatcher(xpath).forward(request, response);33   }34 35   @Override36   public void doPost(HttpServletRequest req, HttpServletResponse resp)37       throws ServletException, IOException {38     this.doGet(req, resp);39   }40 }

2. 定义一个ServiceServlet 继承 DispatcherServlet

 1 package controller; 2  3 import javax.servlet.annotation.WebServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6  7 @SuppressWarnings("serial") 8 @WebServlet("/pages/*") 9 public class ServiceServlet extends DispatcherServlet {10   public String list(HttpServletRequest req, HttpServletResponse resp){11     System.out.println("业务操作---------------");12     return "/WEB-INF/view/list.jsp";13   }14 }

3. JSP页面自定义

4. 访问路径: http://localhost:8080/ReflectServlet/pages/list

5. 其他页面可拓展添加