⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dispatcherservlet.java

📁 MVC的实例
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            if(obj==null)
                continue;
            Class<Action> actionClass = (Class<Action>) obj.getClass();
            Annotation ann = key.getAnnotation();
            if(ann instanceof Named) {
                Named named = (Named) ann;
                String url = named.value();
                if(url!=null)
                    url = url.trim();
                if(!"".equals(url)) {
                    log.info("Bind action [" + actionClass.getName() + "] to URL: " + url);
                    // link url with this action:
                    urlMapping.put(url, new ActionAndMethod(key, actionClass));
                }
                else {
                    log.warn("Cannot bind action [" + actionClass.getName() + "] to *EMPTY* URL.");
                }
            }
            else {
                log.warn("Cannot bind action [" + actionClass.getName() + "] because no @Named annotation found in config module. Using: binder.bind(MyAction.class).annotatedWith(Names.named(\"/url\"));");
            }
        }
        return urlMapping;
    }

    /**
     * Get a config module for IoC config. NOTE that all Action classes must 
     * bind with annotation of @Named("url") with a valid url.
     * 
     * @return A config module.
     */
    protected Module getConfigModule(String className, ServletContext context) throws ServletException {
        Object obj = null;
        try {
            Class<?> clazz = Class.forName(className);
            obj = clazz.newInstance();
        }
        catch(InstantiationException e) {
            throw new ServletException("Cannot instantiat for class \"" + className + "\"", e);
        }
        catch(IllegalAccessException e) {
            throw new ServletException("Cannot instantiat for class \"" + className + "\"", e);
        }
        catch(ClassNotFoundException e) {
            throw new ServletException("Cannot find class \"" + className + "\"", e);
        }
        try {
            Module module = (Module)obj;
            if(module instanceof ServletContextAware) {
                ((ServletContextAware)module).setServletContext(context);
            }
            return module;
        }
        catch(ClassCastException e) {
            throw new ServletException("Cannot cast class \"" + className + "\" to \"" + Module.class.getName() + "\"", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // find mvc:
        String contextPath = request.getContextPath();
        String url = request.getRequestURI().substring(contextPath.length());
        if(log.isDebugEnabled())
            log.debug("Handle for URL: " + url);
        ActionAndMethod am = actionMap.get(url);
        if(am==null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ModelAndView mv = null;
        try {
            // init ActionContext:
            HttpSession session = request.getSession();
            ServletContext context = session.getServletContext();
            ActionContext.setActionContext(request, response, session, context);
            // try instance action:
            Action action = (Action) injector.getInstance(am.getKey());
            if(log.isDebugEnabled()) {
                log.debug("Found action for URL \"" + url + "\": " + action);
                log.debug("Bind parameters to action: " + action);
            }
            // try to invoke all setters:
            List<String> props = am.getProperties();
            for(String prop : props) {
                String value = request.getParameter(prop);
                if(value!=null) {
                    // only invoke with non-null value:
                    am.invokeSetter(action, prop, value);
                }
            }
            // now apply all interceptors and invoke execute:
            if(log.isDebugEnabled())
                log.debug("Apply Interceptors...");
            InterceptorChainImpl chains = new InterceptorChainImpl(interceptors);
            try {
                chains.doInterceptor(action);
                mv = chains.getModelAndView();
            }
            catch(Exception e) {
                if(log.isDebugEnabled())
                    log.debug("Handle exception: " + e);
                if(exceptionResolver!=null) {
                    try {
                        mv = exceptionResolver.handleException(action, e);
                    }
                    catch(Exception ex) {
                        throw new ServletException("Exception when handle request.", e);
                    }
                }
                else
                    throw new ServletException("Exception when handle request.", e);
            }
            catch(Throwable t) {
                throw new ServletException(t);
            }
        }
        finally {
            ActionContext.remove();
        }
        // render view:
        if(mv!=null)
            render(mv, request, response);
    }

    // render view:
    private void render(ModelAndView mv, HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        String view = mv.getView();
        if(view.startsWith("redirect:")) {
            String redirect = view.substring("redirect:".length());
            if(log.isDebugEnabled())
                log.debug("Send a redirect to: " + redirect);
            response.sendRedirect(redirect);
            return;
        }
        Map<String, Object> model = mv.getModel();
        if(log.isDebugEnabled())
            log.debug("Render view: " + view);
        if(viewResolver!=null)
            viewResolver.resolveView(view, model, reqest, response);
    }

    /**
     * Call to doGet(request, response).
     */
    @Override
    protected void doPost(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        doGet(reqest, response);
    }

    //--------------------------------------------------------------------------
    // All method are rejected except GET and POST
    //--------------------------------------------------------------------------

    /**
     * Send an HttpServletResponse.SC_BAD_REQUEST error.
     */
    @Override
    protected void doDelete(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

    /**
     * Send an HttpServletResponse.SC_BAD_REQUEST error.
     */
    @Override
    protected void doHead(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

    /**
     * Send an HttpServletResponse.SC_BAD_REQUEST error.
     */
    @Override
    protected void doOptions(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

    /**
     * Send an HttpServletResponse.SC_BAD_REQUEST error.
     */
    @Override
    protected void doPut(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

    /**
     * Send an HttpServletResponse.SC_BAD_REQUEST error.
     */
    @Override
    protected void doTrace(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -