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

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

Introduction

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

Prototype

@Nullable
public String getViewName() 

Source Link

Document

Return the view name to be resolved by the DispatcherServlet via a ViewResolver, or null if we are using a View object.

Usage

From source file:org.jamwiki.servlets.JAMWikiServlet.java

/**
 * This method ensures that values required for rendering a JSP page have been
 * loaded into the ModelAndView object. Examples of values that may be handled
 * by this method include topic name, username, etc.
 * /*w w w  .  j ava  2 s. c om*/
 * @param request
 *          The current servlet request object.
 * @param next
 *          The current ModelAndView object.
 * @param pageInfo
 *          The current WikiPageInfo object, containing basic page rendering
 *          information.
 */
private void loadLayout(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    if (next.getViewName() != null && next.getViewName().startsWith(ServletUtil.SPRING_REDIRECT_PREFIX)) {
        // if this is a redirect, no need to load anything
        return;
    }
    // load cached top area, nav bar, etc.
    this.buildLayout(request, next, pageInfo);
    if (StringUtils.isBlank(pageInfo.getTopicName())) {
        pageInfo.setTopicName(WikiUtil.getTopicFromURI(request));
    }
    pageInfo.setUserMenu(this.buildUserMenu(pageInfo));
    pageInfo.setTabMenu(this.buildTabMenu(request, pageInfo));
}

From source file:org.jasig.cas.web.StatisticsController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws Exception {
    final ModelAndView modelAndView = new ModelAndView(new InternalResourceView(viewPath));
    modelAndView.addObject("startTime", this.upTimeStartDate);
    final double difference = System.currentTimeMillis() - this.upTimeStartDate.getTime();

    modelAndView/*  w w  w.j  a  va2s  .  c  o m*/
            .addObject("upTime",
                    calculateUptime(difference,
                            new LinkedList<Integer>(Arrays.asList(NUMBER_OF_MILLISECONDS_IN_A_DAY,
                                    NUMBER_OF_MILLISECONDS_IN_AN_HOUR, NUMBER_OF_MILLISECONDS_IN_A_MINUTE,
                                    NUMBER_OF_MILLISECONDS_IN_A_SECOND, 1)),
                            new LinkedList<String>(
                                    Arrays.asList("day", "hour", "minute", "second", "millisecond"))));

    modelAndView.addObject("totalMemory", convertToMegaBytes(Runtime.getRuntime().totalMemory()));
    modelAndView.addObject("maxMemory", convertToMegaBytes(Runtime.getRuntime().maxMemory()));
    modelAndView.addObject("freeMemory", convertToMegaBytes(Runtime.getRuntime().freeMemory()));
    modelAndView.addObject("availableProcessors", Runtime.getRuntime().availableProcessors());
    modelAndView.addObject("serverHostName", httpServletRequest.getServerName());
    modelAndView.addObject("serverIpAddress", httpServletRequest.getLocalAddr());
    modelAndView.addObject("casTicketSuffix", this.casTicketSuffix);

    int unexpiredTgts = 0;
    int unexpiredSts = 0;
    int expiredTgts = 0;
    int expiredSts = 0;

    try {
        final Collection<Ticket> tickets = this.centralAuthenticationService
                .getTickets(TruePredicate.getInstance());

        for (final Ticket ticket : tickets) {
            if (ticket instanceof ServiceTicket) {
                if (ticket.isExpired()) {
                    expiredSts++;
                } else {
                    unexpiredSts++;
                }
            } else {
                if (ticket.isExpired()) {
                    expiredTgts++;
                } else {
                    unexpiredTgts++;
                }
            }
        }
    } catch (final UnsupportedOperationException e) {
        logger.trace("The ticket registry doesn't support this information.");
    }

    final Collection<GraphingStatisticsAppender> appenders = GraphingStatisticsAppender
            .getAllGraphingStatisticsAppenders();

    modelAndView.addObject("unexpiredTgts", unexpiredTgts);
    modelAndView.addObject("unexpiredSts", unexpiredSts);
    modelAndView.addObject("expiredTgts", expiredTgts);
    modelAndView.addObject("expiredSts", expiredSts);
    modelAndView.addObject("pageTitle", modelAndView.getViewName());
    modelAndView.addObject("graphingStatisticAppenders", appenders);

    return modelAndView;
}

From source file:org.jasig.cas.web.support.ThrottledSubmissionByIpAddressHandlerInterceptorAdapter.java

public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final ModelAndView modelAndView) throws Exception {
    if (!request.getMethod().equals("GET") || !"casLoginView".equals(modelAndView.getViewName())) {
        return;//from   w  w w  .  j  a  v a 2 s  .  c  om
    }
    final String remoteAddr = request.getRemoteAddr();

    // workaround for the IPv6 bug in the original adapter. See CAS-639
    try {
        final String lastQuad = remoteAddr.substring(remoteAddr.lastIndexOf(".") + 1);
        final int intVersionOfLastQuad = Integer.parseInt(lastQuad);
        final Map<String, BigInteger> quadMap = this.restrictedIpAddressMaps[intVersionOfLastQuad - 1];

        synchronized (quadMap) {
            final BigInteger original = quadMap.get(lastQuad);
            BigInteger integer = ONE;

            if (original != null) {
                integer = original.add(ONE);
            }

            quadMap.put(lastQuad, integer);

            if (integer.compareTo(this.failureThreshhold) == 1) {
                log.warn("Possible hacking attack from " + remoteAddr + ". More than " + this.failureThreshhold
                        + " failed login attempts within " + this.failureTimeout + " seconds.");
                modelAndView.setViewName("casFailureAuthenticationThreshhold");
            }
        }
    } catch (NumberFormatException e) {
        log.warn(
                "Skipping ip-address blocking. Possible reason: IPv6 Address not supported: " + e.getMessage());
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}

From source file:org.jtalks.jcommune.web.interceptors.SapeInterceptor.java

/**
 * Set sape content to request parameters.
 *
 * @param request      current HTTP request
 * @param response     current HTTP response
 * @param handler      chosen handler to execute, for type and/or instance examination
 * @param modelAndView the {@code ModelAndView} that the handler returned (can also be {@code null})
 *///w ww .  ja v  a  2s .  com
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    if (!componentSapeEnableServiceProperty.booleanValue() || modelAndView == null
            || modelAndView.getViewName() == null ||
            //do not apply to the redirected requests: it's unnecessary and may cause error pages to work
            // incorrectly
            (!componentSapeOnMainPageEnableProperty.booleanValue()
                    && modelAndView.getViewName().equals("sectionList"))
            || modelAndView.getViewName().contains("redirect:")) {
        return;
    }

    String sapeLinksAsString = "";
    if (componentSapeShowDummyLinksProperty.booleanValue()) {
        sapeLinksAsString = dummyLinks;
    } else if (initSape()) {
        SapePageLinks pageLinks = sape.getPageLinks(request.getRequestURI(), request.getCookies());
        sapeLinksAsString = pageLinks.render();
    }
    modelAndView.addObject("sapeLinks", sapeLinksAsString);
}

From source file:org.kuali.rice.krad.uif.util.UifWebUtils.java

/**
 * After the controller logic is executed, the form is placed into session
 * and the corresponding view is prepared for rendering
 *//*from ww  w  .  j  a  v a2s . co m*/
public static void postControllerHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView) throws Exception {
    if (handler instanceof UifControllerBase && (modelAndView != null)) {
        UifControllerBase controller = (UifControllerBase) handler;
        UifFormBase form = null;

        // check to see if this is a full view request
        if (modelAndView.getViewName().equals(UifConstants.SPRING_VIEW_ID)) {
            Object model = modelAndView.getModelMap().get(UifConstants.DEFAULT_MODEL_NAME);
            if (model instanceof UifFormBase) {
                form = (UifFormBase) model;

                // prepare view instance
                prepareViewForRendering(request, form);

                // update history for view
                prepareHistory(request, form);
            }
        }
    }
}

From source file:org.nextframework.controller.MultiActionController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {//  w w  w  .j  av a 2 s.co m
        WebRequestContext requestContext = NextWeb.getRequestContext(request, response);
        Method method = this.methodNameResolver.getHandlerMethod(request);
        request.setAttribute("firstAction", requestContext.getLastAction());
        ModelAndView result = invokeNamedMethod(method, requestContext, null);

        while (result != null && result.getViewName() != null && result.getViewName().startsWith("action:")) {
            String actionName = result.getViewName().substring("action:".length(),
                    result.getViewName().length());

            method = this.methodNameResolver.getHandlerMethod(actionName);
            result = invokeNamedMethod(method, requestContext, null);
        }
        request.setAttribute("lastAction", requestContext.getLastAction());
        return result;
    } catch (NoSuchRequestHandlingMethodException ex) {
        return noSuchMethodHandler(request, response, ex);
    } catch (NoActionHandlerException e) {
        return noActionHandler(request, response, e);
    }
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Continua o processamento em outra action, utilizando o mesmo command. 
 * @param action/* w w  w.j  a  va 2  s .  co m*/
 * @param command
 * @return
 */
protected ModelAndView continueOnAction(String action, Object command) {
    WebRequestContext request = NextWeb.getRequestContext();
    ((DefaultWebRequestContext) request).setLastAction(action);

    HttpServletResponse servletResponse = request.getServletResponse();
    try {
        Method method = this.methodNameResolver.getHandlerMethod(action);

        ModelAndView result = invokeNamedMethod(method,
                NextWeb.getRequestContext(request.getServletRequest(), servletResponse), command);
        request.setAttribute("firstAction", request.getLastAction());
        while (result != null && result.getViewName() != null && result.getViewName().startsWith("action:")) {
            String actionName = result.getViewName().substring("action:".length(),
                    result.getViewName().length());

            method = this.methodNameResolver.getHandlerMethod(actionName);
            result = invokeNamedMethod(method, request, command);
        }
        request.setAttribute("lastAction", request.getLastAction());
        return result;
    } catch (NoSuchRequestHandlingMethodException ex) {
        pageNotFoundLogger.warn(ex.getMessage());
        try {
            servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Invoke the selected exception handler.
 * //w w  w  .j  a va2 s .c  om
 * @param handler
 *            handler method to invoke
 */
private ModelAndView invokeExceptionHandler(Method handler, WebRequestContext request, Throwable ex)
        throws Exception {

    if (handler == null) {
        throw new ServletException("No handler for exception", ex);
    }

    // If we get here, we have a handler.
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking exception handler [" + handler + "] for exception [" + ex + "]");
    }
    try {
        Object result = handler.invoke(this.delegate, new Object[] { request, ex });
        ModelAndView mv = convertActionResultToModelAndView(handler, result);
        while (mv != null && mv.getViewName() != null && mv.getViewName().startsWith("action:")) {
            String actionName = mv.getViewName().substring("action:".length(), mv.getViewName().length());
            Method method = this.methodNameResolver.getHandlerMethod(actionName);
            mv = invokeNamedMethod(method, request, null);
        }
        return mv;
    } catch (InvocationTargetException ex2) {
        Throwable targetEx = ex2.getTargetException();
        if (targetEx instanceof Exception) {
            throw (Exception) targetEx;
        }
        if (targetEx instanceof Error) {
            throw (Error) targetEx;
        }
        // shouldn't happen
        throw new ServletException("Unknown Throwable type encountered", targetEx);
    }
}

From source file:org.openlegacy.rpc.mvc.web.interceptors.InsertEntityDefinitionsInterceptor.java

@Override
protected void insertModelData(ModelAndView modelAndView, HttpServletRequest request,
        HttpServletResponse response) {//from   www .ja v a 2  s.  c om
    String modelName = StringUtils.uncapitalize(modelAndView.getViewName());
    Object model = modelAndView.getModel().get(modelName);
    if (model != null && model instanceof RpcEntity) {
        mvcUtils.insertModelObjects(modelAndView, model, entitiesRegistry);
    } else {
        PageDefinition page = (PageDefinition) modelAndView.getModel().get("page");
        if (page != null) {

            EntityDefinition<?> definitions = page.getEntityDefinition();
            model = modelAndView.getModel().get(StringUtils.uncapitalize(definitions.getEntityName()));
            if (model != null && model instanceof RpcEntity) {
                // mvcUtils.insertModelObjects(modelAndView, model, definitions);
                modelAndView.addObject("definitions", definitions);
                List<Object> keysValues = EntityUtils.getKeysValues(model, definitions);
                String keysValuesText = StringUtil.toString(keysValues, '_');
                modelAndView.addObject("ol_entityId", keysValuesText);
                modelAndView.addObject("ol_entityUniqueId", definitions.getEntityName() + keysValuesText);
            }
        }
    }
    if (entitiesRegistry.isDirty()) {
        // set the registry back to clean - for design-time purposes only!
        ((AbstractEntitiesRegistry<?, ?, ?>) entitiesRegistry).setDirty(false);
    }

    Menu menuModule = getSession().getModule(Menu.class);
    if (menuModule != null) {
        modelAndView.addObject("ol_menu", menuModule.getMenuTree());
        modelAndView.addObject("ol_flatMenus", menuModule.getFlatMenuEntries());
    }
}

From source file:org.openmrs.module.radiology.legacyui.report.template.web.RadiologyDashboardReportTemplatesTabControllerTest.java

@Test
public void shouldReturnModelAndViewOfTheRadiologyReportTemplatesTabPageAndSetTabSessionAttributeToRadiologyReportsTabPage()
        throws Exception {

    MockHttpSession mockSession = new MockHttpSession();
    request.setSession(mockSession);//from  w  w  w. j a v  a2 s  .c o m

    ModelAndView modelAndView = radiologyDashboardReportTemplatesTabController
            .getRadiologyReportTemplatesTab(request);

    verifyZeroInteractions(mrrtReportTemplateService);

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(),
            is(RadiologyDashboardReportTemplatesTabController.RADIOLOGY_REPORT_TEMPLATES_TAB_VIEW));
    assertThat(mockSession.getAttribute(RadiologyWebConstants.RADIOLOGY_DASHBOARD_TAB_SESSION_ATTRIBUTE),
            is(RadiologyDashboardReportTemplatesTabController.RADIOLOGY_REPORT_TEMPLATES_TAB_REQUEST_MAPPING));
}