星空网 > 软件开发 > 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. 其他页面可拓展添加

 




原标题:java 反射机制 Demo 练习

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

亚马逊澳洲站将在悉尼开设第二个配送中心:https://www.goluckyvip.com/news/95.html
25%关税来袭,跨境电商物流的变革与机遇:https://www.goluckyvip.com/news/950.html
怎么回事?关闭99个仓库,却又计划拓展至少150个站点! :https://www.goluckyvip.com/news/9500.html
政企联动|鄂州市国资委代表来SHOPLINE物流参观考察 :https://www.goluckyvip.com/news/9501.html
Shopee、速卖通、Lazada、美客多测评自养号,如何提升产品曝光量和出单量 :https://www.goluckyvip.com/news/9502.html
跨境物流如何处理复杂的运输法律? :https://www.goluckyvip.com/news/9503.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流