Example usage for org.springframework.web.servlet ModelAndView hasView

List of usage examples for org.springframework.web.servlet ModelAndView hasView

Introduction

In this page you can find the example usage for org.springframework.web.servlet ModelAndView hasView.

Prototype

public boolean hasView() 

Source Link

Document

Indicate whether or not this ModelAndView has a view, either as a view name or as a direct View instance.

Usage

From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java

/**
 * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
 * @param request current HTTP request//from  w  w  w . j a  v  a 2s  .c  o  m
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen at the time of the exception
 * (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution
 * @return a corresponding ModelAndView to forward to
 * @throws Exception if no error ModelAndView found
 */
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) throws Exception {

    // Check registered HandlerExceptionResolvers...
    ModelAndView exMv = null;
    for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {
        exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);
        if (exMv != null) {
            break;
        }
    }
    if (exMv != null) {
        if (exMv.isEmpty()) {
            return null;
        }
        // We might still need view name translation for a plain error model...
        if (!exMv.hasView()) {
            exMv.setViewName(getDefaultViewName(request));
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv,
                    ex);
        }
        WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
        return exMv;
    }

    throw ex;
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.DelegatingController.java

/**
 * Determine a handler method and invoke it.
 * @see MethodNameResolver#getHandlerMethodName
 * @see #invokeNamedMethod//from  ww w . j av  a 2  s  . c om
 * @see #handleNoSuchRequestHandlingMethod
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {
        // TODO improve error checks
        Object command = getCommandObject(request, commandClass);

        Map<String, Object> components = new HashMap<String, Object>();

        // check the command objects for components
        if (command instanceof SubCommandProvider) {
            SubCommandProvider cp = (SubCommandProvider) command;
            components = cp.getSubCommands();
        }

        // add the 'default' component, this is the 'root' command object at the root path
        components.put("", command);
        components = prepareComponentPathForLookup(components);

        // build a map of containing pathNames and their handlers
        Map<String, List<WebComponent>> handlersForPath = new HashMap<String, List<WebComponent>>();
        for (Entry<String, Object> component : components.entrySet()) {
            for (WebComponent handler : this.delegates) {
                if (component.getValue() != null && handler.supports(component.getValue())) {
                    List<WebComponent> handlers = handlersForPath.get(component.getKey());
                    if (handlers == null) {
                        handlers = new ArrayList<WebComponent>();
                        handlersForPath.put(component.getKey(), handlers);
                    }
                    handlers.add(handler);
                }
            }
        }

        WebActionToken token = actionResolver.getAction(request, components.keySet(), handlersForPath);

        ComponentDataBinder binder = createBinder(request, command);
        ModelAndView mav = new ModelAndView(getFormView(), binder.getBindingResult().getModel());

        if (token != null) { // we found a command in one of the components and delegate action to handler
            ComponentToken comToken = new ComponentToken();
            comToken.setComponent(components.get(token.getPathName()));
            comToken.setToken(token);
            comToken.setBinder(binder);
            logger.info("Processing input " + comToken);
            Object rv = token.getHandler().excecuteAction(request, response, comToken);
            mav = massageReturnValueIfNecessary(rv);
            if (mav != null && !mav.hasView()) {
                mav.setViewName(getFormView());
            }
        }
        postProcessModel(request, mav);
        return mav;
    }

    catch (NoSuchRequestHandlingMethodException ex) {
        return handleNoSuchRequestHandlingMethod(ex, request, response);
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.DelegatingController.java

/**
 * Processes the return value of a handler method to ensure that it either returns
 * <code>null</code> or an instance of {@link ModelAndView}. When returning a {@link Map},
 * the {@link Map} instance is wrapped in a new {@link ModelAndView} instance.
 *///w  w  w.  j  a  v a2 s .c  om
@SuppressWarnings("unchecked")
protected ModelAndView massageReturnValueIfNecessary(Object returnValue) {
    if (returnValue instanceof ModelAndView) {
        ModelAndView mav = (ModelAndView) returnValue;
        if (mav.getView() instanceof RedirectView) {
            RedirectView view = (RedirectView) mav.getView();
            String fragment = "";
            String url = view.getUrl();
            if (StringUtils.hasText(url) && url.startsWith("#")) { // check if url begins with jump to anchor
                fragment = url;
                url = "";
            }
            if (!StringUtils.hasText(url)) {
                url = getRedirectUrl();
                if (StringUtils.hasText(fragment)) {
                    url = url + fragment;
                }
                // NOTE: do NOT expose model attributes as part of the url for internal redirection
                mav.setView(new RedirectView(url, true, true, false));
            }
            return mav;
        } else {
            if (!mav.hasView()) {
                mav.setViewName(getFormView());
            }
            return mav;
        }
    } else if (returnValue instanceof Map) {
        return new ModelAndView(getFormView(), (Map) returnValue);
    } else if (returnValue instanceof String) {
        return new ModelAndView((String) returnValue);
    } else {
        // Either returned null or was 'void' return.
        // We'll assume that the handle method already wrote the response.
        return null;
    }
}

From source file:org.springframework.web.servlet.DispatcherServlet.java

/**
 * Do we need view name translation?//from   ww w.j  a v  a  2  s.c  o m
 */
private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws Exception {
    if (mv != null && !mv.hasView()) {
        String defaultViewName = getDefaultViewName(request);
        if (defaultViewName != null) {
            mv.setViewName(defaultViewName);
        }
    }
}

From source file:org.springframework.web.servlet.DispatcherServlet.java

/**
 * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
 * @param request current HTTP request/*from w  w  w  . j a v  a 2  s . c  om*/
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen at the time of the exception
 * (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution
 * @return a corresponding ModelAndView to forward to
 * @throws Exception if no error ModelAndView found
 */
@Nullable
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
        @Nullable Object handler, Exception ex) throws Exception {

    // Check registered HandlerExceptionResolvers...
    ModelAndView exMv = null;
    if (this.handlerExceptionResolvers != null) {
        for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {
            exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);
            if (exMv != null) {
                break;
            }
        }
    }
    if (exMv != null) {
        if (exMv.isEmpty()) {
            request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
            return null;
        }
        // We might still need view name translation for a plain error model...
        if (!exMv.hasView()) {
            String defaultViewName = getDefaultViewName(request);
            if (defaultViewName != null) {
                exMv.setViewName(defaultViewName);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv,
                    ex);
        }
        WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
        return exMv;
    }

    throw ex;
}

From source file:org.springframework.web.servlet.DispatcherServletMod.java

private void applyViewNameFromViewNameMappings(HandlerExecutionChain mappedHandler, ModelAndView mv)
        throws Exception {
    if (mv == null)
        return;/*ww  w.  jav  a2  s .  c o  m*/
    if (STATUS_OK.equals(mv.getViewName())) {
        mv.setView(null);
    }
    if (mv != null && !mv.hasView()) {
        Object handler = mappedHandler.getHandler();
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String viewName = null;
            for (Entry<HandlerMethod, String> entry : viewNameMappings.entrySet()) {
                if (entry.getKey().equals(handlerMethod)) {
                    viewName = entry.getValue();
                }
            }
            if (viewName != null) {
                mv.setViewName(viewName);
            }
        }
    }
}

From source file:org.springframework.web.servlet.DispatcherServletMod.java

/**
 * Determine an error ModelAndView via the registered
 * HandlerExceptionResolvers.//from w  w  w.  j  av a  2 s.c  o m
 * 
 * @param request
 *            current HTTP request
 * @param response
 *            current HTTP response
 * @param handler
 *            the executed handler, or {@code null} if none chosen at the
 *            time of the exception (for example, if multipart resolution
 *            failed)
 * @param ex
 *            the exception that got thrown during handler execution
 * @return a corresponding ModelAndView to forward to
 * @throws Exception
 *             if no error ModelAndView found
 */
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) throws Exception {

    // Check registered HandlerExceptionResolvers...
    ModelAndView exMv = null;
    for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {
        exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);
        if (exMv != null) {
            break;
        }
    }
    if (exMv != null) {
        if (exMv.isEmpty()) {
            return null;
        }
        // We might still need view name translation for a plain error
        // model...
        if (!exMv.hasView()) {
            exMv.setViewName(getDefaultViewName(request));
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv,
                    ex);
        }
        WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
        return exMv;
    }

    throw ex;
}

From source file:org.springframework.web.servlet.LogDispatcherServlet.java

/**
 * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
 * @param request current HTTP request/*from   w  ww.j  a  va  2 s.  c om*/
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen at the time of the exception
 * (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution
 * @return a corresponding ModelAndView to forward to
 * @throws Exception if no error ModelAndView found
 */
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) throws Exception {

    // Check registered HandlerExceptionResolvers...
    ModelAndView exMv = null;
    for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {
        exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);
        if (exMv != null) {
            break;
        }
    }
    if (exMv != null) {
        if (exMv.isEmpty()) {
            request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
            return null;
        }
        // We might still need view name translation for a plain error model...
        if (!exMv.hasView()) {
            exMv.setViewName(getDefaultViewName(request));
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv,
                    ex);
        }
        WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
        return exMv;
    }

    throw ex;
}

From source file:org.springframework.web.servlet.MyDispatcherServlet.java

/**
 * Process the actual dispatching to the handler.
 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
 * to find the first that supports the handler class.
 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
 * themselves to decide which methods are acceptable.
 * @param request current HTTP request/*  w  w  w  .  j ava2 s  .  c o m*/
 * @param response current HTTP response
 * @throws Exception in case of any kind of processing failure
 */
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    int interceptorIndex = -1;

    try {
        ModelAndView mv;
        boolean errorView = false;

        try {
            processedRequest = checkMultipart(request);

            // Determine handler for the current request.
            mappedHandler = getHandler(processedRequest, false);
            if (mappedHandler == null || mappedHandler.getHandler() == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            // Determine handler adapter for the current request.
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

            // Process last-modified header, if supported by the handler.
            String method = request.getMethod();
            boolean isGet = "GET".equals(method);
            if (isGet || "HEAD".equals(method)) {
                long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                if (logger.isDebugEnabled()) {
                    String requestUri = urlPathHelper.getRequestUri(request);
                    logger.debug("Last-Modified value for [" + requestUri + "] is: " + lastModified);
                }
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }

            // Apply preHandle methods of registered interceptors.
            HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
            if (interceptors != null) {
                for (int i = 0; i < interceptors.length; i++) {
                    HandlerInterceptor interceptor = interceptors[i];
                    if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
                        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response,
                                null);
                        return;
                    }
                    interceptorIndex = i;
                }
            }

            // Actually invoke the handler.
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            // Do we need view name translation?
            if (mv != null && !mv.hasView()) {
                mv.setViewName(getDefaultViewName(request));
            }

            // Apply postHandle methods of registered interceptors.
            if (interceptors != null) {
                for (int i = interceptors.length - 1; i >= 0; i--) {
                    HandlerInterceptor interceptor = interceptors[i];
                    interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
                }
            }
        } catch (ModelAndViewDefiningException ex) {
            logger.debug("ModelAndViewDefiningException encountered", ex);
            mv = ex.getModelAndView();
        } catch (Exception ex) {
            Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
            mv = processHandlerException(processedRequest, response, handler, ex);
            errorView = (mv != null);
        }

        // Did the handler return a view to render?
        if (mv != null && !mv.wasCleared()) {
            render(mv, processedRequest, response);
            if (errorView) {
                WebUtils.clearErrorRequestAttributes(request);
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName()
                        + "': assuming HandlerAdapter completed request handling");
            }
        }

        // Trigger after-completion for successful outcome.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
    }

    catch (Exception ex) {
        // Trigger after-completion for thrown exception.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
        throw ex;
    } catch (Error err) {
        ServletException ex = new NestedServletException("Handler processing failed", err);
        // Trigger after-completion for thrown exception.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
        throw ex;
    }

    finally {
        // Clean up any resources used by a multipart request.
        if (processedRequest != request) {
            cleanupMultipart(processedRequest);
        }
    }
}

From source file:org.springframework.web.servlet.SimpleDispatcherServlet.java

/**
 * Process the actual dispatching to the handler.
 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
 * to find the first that supports the handler class.
 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
 * themselves to decide which methods are acceptable.
 * @param request current HTTP request/* w  w w . java 2  s . c o m*/
 * @param response current HTTP response
 * @throws Exception in case of any kind of processing failure
 */
public void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    int interceptorIndex = -1;

    try {
        ModelAndView mv;
        boolean errorView = false;

        try {
            processedRequest = checkMultipart(request);

            // Determine handler for the current request.
            mappedHandler = getHandler(processedRequest, false);
            if (mappedHandler == null || mappedHandler.getHandler() == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            // Apply preHandle methods of registered interceptors.
            HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
            if (interceptors != null) {
                for (int i = 0; i < interceptors.length; i++) {
                    HandlerInterceptor interceptor = interceptors[i];
                    if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
                        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response,
                                null);
                        return;
                    }
                    interceptorIndex = i;
                }
            }

            // Actually invoke the handler.
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            // Do we need view name translation?
            if (mv != null && !mv.hasView()) {
                mv.setViewName(getDefaultViewName(request));
            }

            // Apply postHandle methods of registered interceptors.
            if (interceptors != null) {
                for (int i = interceptors.length - 1; i >= 0; i--) {
                    HandlerInterceptor interceptor = interceptors[i];
                    interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
                }
            }
        } catch (ModelAndViewDefiningException ex) {
            logger.debug("ModelAndViewDefiningException encountered", ex);
            mv = ex.getModelAndView();
        } catch (Exception ex) {
            Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
            mv = processHandlerException(processedRequest, response, handler, ex);
            errorView = (mv != null);
        }

        // Did the handler return a view to render?
        if (mv != null && !mv.wasCleared()) {
            render(mv, processedRequest, response);
            if (errorView) {
                WebUtils.clearErrorRequestAttributes(request);
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName()
                        + "': assuming HandlerAdapter completed request handling");
            }
        }

        // Trigger after-completion for successful outcome.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
    }

    catch (Exception ex) {
        // Trigger after-completion for thrown exception.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
        throw ex;
    } catch (Error err) {
        ServletException ex = new NestedServletException("Handler processing failed", err);
        // Trigger after-completion for thrown exception.
        triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
        throw ex;
    }

    finally {
        // Clean up any resources used by a multipart request.
        if (processedRequest != request) {
            cleanupMultipart(processedRequest);
        }
    }
}