List of usage examples for org.springframework.web.servlet ModelAndView getViewName
@Nullable
public String getViewName()
From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java
@Test public void requestReplyWithFullMessageInModel() throws Exception { DirectChannel requestChannel = new DirectChannel(); AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { @Override//from w w w .ja v a 2 s . c om protected Object handleRequestMessage(Message<?> requestMessage) { return requestMessage.getPayload().toString().toUpperCase(); } }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); controller.setBeanFactory(mock(BeanFactory.class)); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.setExtractReplyPayload(false); controller.afterPropertiesSet(); controller.start(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); request.setContent("abc".getBytes()); //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE //Instead do: request.addHeader("Content-Type", "text/plain"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView modelAndView = controller.handleRequest(request, response); assertEquals("foo", modelAndView.getViewName()); assertEquals(1, modelAndView.getModel().size()); Object reply = modelAndView.getModel().get("reply"); assertNotNull(reply); assertTrue(reply instanceof Message<?>); assertEquals("ABC", ((Message<?>) reply).getPayload()); }
From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java
@Test public void shutDown() throws Exception { DirectChannel requestChannel = new DirectChannel(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { @Override//from ww w . j a va 2 s . c om protected Object handleRequestMessage(Message<?> requestMessage) { try { latch2.countDown(); // hold up an active thread so we can verify the count and that it completes ok latch1.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return requestMessage.getPayload().toString().toUpperCase(); } }; requestChannel.subscribe(handler); final HttpRequestHandlingController controller = new HttpRequestHandlingController(true); controller.setBeanFactory(mock(BeanFactory.class)); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.afterPropertiesSet(); controller.start(); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); request.setContent("hello".getBytes()); //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE //Instead do: request.addHeader("Content-Type", "text/plain"); MockHttpServletResponse response = new MockHttpServletResponse(); final AtomicInteger active = new AtomicInteger(); final AtomicBoolean expected503 = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(() -> { try { // wait for the active thread latch2.await(10, TimeUnit.SECONDS); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } // start the shutdown active.set(controller.beforeShutdown()); try { MockHttpServletResponse response1 = new MockHttpServletResponse(); controller.handleRequest(request, response1); expected503.set(response1.getStatus() == HttpStatus.SERVICE_UNAVAILABLE.value()); latch1.countDown(); } catch (Exception e) { LogFactory.getLog(getClass()).error("Async handleRequest failed", e); } }); ModelAndView modelAndView = controller.handleRequest(request, response); // verify we get a 503 after shutdown starts assertEquals(1, active.get()); assertTrue(expected503.get()); // verify the active request still processed ok assertEquals("foo", modelAndView.getViewName()); assertEquals(1, modelAndView.getModel().size()); Object reply = modelAndView.getModel().get("reply"); assertNotNull(reply); assertEquals("HELLO", reply); }
From source file:org.springframework.web.portlet.DispatcherPortlet.java
/** * Render the given ModelAndView. This is the last stage in handling a request. * It may involve resolving the view by name. * @param mv the ModelAndView to render/* w ww . j ava2 s . c o m*/ * @param request current portlet render request * @param response current portlet render response * @throws Exception if there's a problem rendering the view */ protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { View view; if (mv.isReference()) { // We need to resolve the view name. view = resolveViewName(mv.getViewName(), mv.getModelInternal(), request); if (view == null) { throw new PortletException("Could not resolve view with name '" + mv.getViewName() + "' in portlet with name '" + getPortletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual View object. Object viewObject = mv.getView(); if (viewObject == null) { throw new PortletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in portlet with name '" + getPortletName() + "'"); } if (!(viewObject instanceof View)) { throw new PortletException("View object [" + viewObject + "] is not an instance of [org.springframework.web.servlet.View] - " + "DispatcherPortlet does not support any other view types"); } view = (View) viewObject; } // Set the content type on the response if needed and if possible. // The Portlet spec requires the content type to be set on the RenderResponse; // it's not sufficient to let the View set it on the ServletResponse. if (response.getContentType() != null) { if (logger.isDebugEnabled()) { logger.debug("Portlet response content type already set to [" + response.getContentType() + "]"); } } else { // No Portlet content type specified yet -> use the view-determined type. String contentType = view.getContentType(); if (contentType != null) { if (logger.isDebugEnabled()) { logger.debug( "Setting portlet response content type to view-determined type [" + contentType + "]"); } response.setContentType(contentType); } } doRender(view, mv.getModelInternal(), request, response); }
From source file:org.springframework.web.servlet.DispatcherServlet.java
/** * Render the given ModelAndView.//from www . java 2 s . c o m * <p>This is the last stage in handling a request. It may involve resolving the view by name. * @param mv the ModelAndView to render * @param request current HTTP servlet request * @param response current HTTP servlet response * @throws ServletException if view is missing or cannot be resolved * @throws Exception if there's a problem rendering the view */ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine locale for request and apply it to the response. Locale locale = (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale()); response.setLocale(locale); View view; String viewName = mv.getViewName(); if (viewName != null) { // We need to resolve the view name. view = resolveViewName(viewName, mv.getModelInternal(), locale, request); if (view == null) { throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual View object. view = mv.getView(); if (view == null) { throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'"); } } // Delegate to the View object for rendering. if (logger.isDebugEnabled()) { logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'"); } try { if (mv.getStatus() != null) { response.setStatus(mv.getStatus().value()); } view.render(mv.getModelInternal(), request, response); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'", ex); } throw ex; } }
From source file:org.springframework.web.servlet.DispatcherServletMod.java
private void applyViewNameFromViewNameMappings(HandlerExecutionChain mappedHandler, ModelAndView mv) throws Exception { if (mv == null) return;// www .ja v a 2 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
/** * Render the given ModelAndView.//from w w w. ja v a 2 s . c o m * <p> * This is the last stage in handling a request. It may involve resolving * the view by name. * * @param mv * the ModelAndView to render * @param request * current HTTP servlet request * @param response * current HTTP servlet response * @throws ServletException * if view is missing or cannot be resolved * @throws Exception * if there's a problem rendering the view */ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine locale for request and apply it to the response. Locale locale = this.localeResolver.resolveLocale(request); response.setLocale(locale); View view; if (mv.isReference()) { // We need to resolve the view name. view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request); if (view == null) { throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual // View object. view = mv.getView(); if (view == null) { throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'"); } } // Delegate to the View object for rendering. if (logger.isDebugEnabled()) { logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'"); } try { view.render(mv.getModelInternal(), request, response); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'", ex); } throw ex; } }
From source file:org.springframework.web.servlet.LogDispatcherServlet.java
/** * Render the given ModelAndView.//from www .jav a 2s .c om * <p>This is the last stage in handling a request. It may involve resolving the view by name. * @param mv the ModelAndView to render * @param request current HTTP servlet request * @param response current HTTP servlet response * @throws ServletException if view is missing or cannot be resolved * @throws Exception if there's a problem rendering the view */ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine locale for request and apply it to the response. Locale locale = this.localeResolver.resolveLocale(request); response.setLocale(locale); View view; if (mv.isReference()) { // We need to resolve the view name. view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request); if (view == null) { throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual View object. view = mv.getView(); if (view == null) { throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'"); } } // Delegate to the View object for rendering. if (logger.isDebugEnabled()) { logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'"); } try { view.render(mv.getModelInternal(), request, response); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'", ex); } throw ex; } }
From source file:org.springframework.web.servlet.SimpleDispatcherServlet.java
/** * Render the given ModelAndView./*from ww w.j a va 2s . c o m*/ * <p>This is the last stage in handling a request. It may involve resolving the view by name. * @param mv the ModelAndView to render * @param request current HTTP servlet request * @param response current HTTP servlet response * @throws Exception if there's a problem rendering the view */ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine locale for request and apply it to the response. Locale locale = this.localeResolver.resolveLocale(request); response.setLocale(locale); View view; if (mv.isReference()) { // We need to resolve the view name. view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request); if (view == null) { throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual View object. view = mv.getView(); if (view == null) { throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'"); } } //DEBUG Map<String, Object> modelInternal = mv.getModelInternal(); for (String modelName : modelInternal.keySet()) { System.out.println("modelKey: " + modelName); System.out.println("modelValue: " + modelInternal.get(modelName)); } // Delegate to the View object for rendering. if (logger.isDebugEnabled()) { logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'"); } view.render(mv.getModelInternal(), request, response); }
From source file:org.springmodules.xt.ajax.AjaxInterceptor.java
/** * Post-handle the http request and if it was an ajax request firing a submit, looks for a mapped ajax handler, executes it and * returns an ajax response.<br>/*from w w w . j av a 2s.com*/ * If the matching mapped handler returns a null or empty ajax response, the interceptor looks for a view configured with * the {@link #AJAX_REDIRECT_PREFIX} and make a redirect to it; if the configured view has no * {@link #AJAX_REDIRECT_PREFIX}, an exception is thrown. * * @throws UnsupportedEventException If the event associated with this ajax request is not supported by any * mapped handler. * @throws EventHandlingException If an error occurred during event handling. * @throws NoMatchingHandlerException If no mapped handler matching the URL can be found. * @throws IllegalViewException If the view to which redirect to doesn't contain the {@link #AJAX_REDIRECT_PREFIX}. */ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (WebUtils.isIncludeRequest(request)) { return; } try { // If modelAndView object is null, it means that the controller handled the request by itself ... // See : http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/Controller.html#handleRequest(javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse) if (modelAndView == null) { logger.info("Null ModelAndView object, proceeding without Ajax processing ..."); return; } // // Store the model map: this.storeModel(request.getSession(), modelAndView.getModel()); // // Continue processing: // String requestType = request.getParameter(this.ajaxParameter); if (requestType != null && requestType.equals(AJAX_SUBMIT_REQUEST)) { String eventId = request.getParameter(this.eventParameter); if (eventId == null) { throw new IllegalStateException("Event id cannot be null."); } logger.info(new StringBuilder("Post-handling ajax request for event: ").append(eventId)); List<AjaxHandler> handlers = this.lookupHandlers(request); if (handlers.isEmpty()) { throw new NoMatchingHandlerException("Cannot find an handler matching the request: " + this.urlPathHelper.getLookupPathForRequest(request)); } else { AjaxSubmitEvent event = new AjaxSubmitEventImpl(eventId, request); AjaxResponse ajaxResponse = null; boolean supported = false; for (AjaxHandler ajaxHandler : handlers) { if (ajaxHandler.supports(event)) { // Set event properties: this.initEvent(event, request); Map model = this.getModel(request.getSession()); if (model != null) { Object commandObject = this.formDataAccessor.getCommandObject(request, response, handler, model); Errors errors = this.formDataAccessor.getValidationErrors(request, response, handler, model); event.setCommandObject(commandObject); event.setValidationErrors(errors); event.setModel(model); } // Handle event: ajaxResponse = ajaxHandler.handle(event); supported = true; break; } } if (!supported) { throw new UnsupportedEventException("Cannot handling the given event with id: " + eventId); } else { if (ajaxResponse != null && !ajaxResponse.isEmpty()) { // Need to clear the ModelAndView because we are handling the response by ourselves: modelAndView.clear(); AjaxResponseSender.sendResponse(response, ajaxResponse); } else { // No response, so try an Ajax redirect: String view = modelAndView.getViewName(); if (view != null && view.startsWith(AJAX_REDIRECT_PREFIX)) { view = view.substring(AJAX_REDIRECT_PREFIX.length()); this.redirectToView(view, request, response, modelAndView); } else if (view != null && view.startsWith(STANDARD_REDIRECT_PREFIX)) { view = view.substring(STANDARD_REDIRECT_PREFIX.length()); this.redirectToView(view, request, response, modelAndView); } else { throw new IllegalViewException("No Ajax redirect prefix: " + AJAX_REDIRECT_PREFIX + " found for view: " + view); } } } } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); throw ex; } }
From source file:org.squashtest.tm.web.internal.interceptor.SecurityExpressionResolverExposerInterceptor.java
/** * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) *//*from w ww . j av a2 s.c o m*/ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView != null && modelAndView.hasView() && !StringUtils.startsWith(modelAndView.getViewName(), "redirect:")) { FilterInvocation filterInvocation = new FilterInvocation(request, response, DUMMY_CHAIN); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { LOGGER.debug( "No authentication available for '{}{}'. Thymeleaf won't have access to '#sec' in view '{}'", request.getServletPath(), request.getPathInfo(), modelAndView.getViewName()); return; } WebSecurityExpressionRoot expressionRoot = new WebSecurityExpressionRoot(authentication, filterInvocation); expressionRoot.setTrustResolver(trustResolver); expressionRoot.setPermissionEvaluator(permissionEvaluator); modelAndView.addObject("sec", expressionRoot); } }