实现DispatchServlet比spring的好用,哈哈

    技术2022-05-19  21

        “团购网”的实现我用了N个servlet。如果我能只用一个servlet的话,把请求分发给子servlet的话那就牛叉了。

     

    解决方案一:

         在servlet中,用分支语句判断请求的path,来分发请求。Controller是一个接口,其它的Controller实现处理具体的请求。如下代码。

     /** *------------------------DispatchServlet.doGet()----------------------- *分发请求到Controller * */ public void doGet(ServletRequest req,ServletResponse resp) throws IOException,ServletException{ String servletPath = req.getServletPath(); String[] pathArray = servletPath.split("[///.]"); String command = classNameArray[1]; Controller controller = null; if(command.equalse("register")){ controller = new ControllerRegister(); } else if(command.equalse("login")){ controller = new ControllerLogin(); } ... String view = controller.getView(req,resp); req.getRequestDispatcher(view).forward(req, resp); }

        这个方案的缺点是,我没增加一个Controller我就必须更改DispatchServlet.doGet()。要解决这个问题一定不能用分支语句了。因为分支语句的支数是可变的。我必须使用请求路径和Controller的一一映射关系。显然字符串和类的映射就是反射机制。代码如下。

    /** * 执行servlet引擎。 * * @param req * @param resp * @throws ServletException * @throws IOException */ private void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // --- 1. 从request中得到XXX.do字符串 String servletPath = req.getServletPath(); String[] classNameArray = servletPath.split("[///.]"); String className = classNameArray[1]; // --- 2. 通过Class.forName()初始化Controller接口。 Controller controller = null; try { Class<?> nClass = Class.forName("come.on.web."+className); controller = (Controller) (nClass.newInstance()); } catch (Exception e) { } // --- 3. 执行Controller的getView()方法。 String view = controller.getView(req, resp); // --- 4. 用RequestDispatch将转发给.jsp文件。 req.getRequestDispatcher(view).forward(req, resp); }

        这个工具的优点:

            1、不需要配置一一映射关系

            2、可以分发多个Controller。

       缺点是,请求的command必须和类名称相符。

     


    最新回复(0)