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

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

Introduction

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

Prototype

public void setView(@Nullable View view) 

Source Link

Document

Set a View object for this ModelAndView.

Usage

From source file:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java

/**
 * Handle all exceptions of type {@link ImageRepositoryException} thrown by (or passing trough) the Controller's layer
 * //w w w.  ja v  a2 s. c o  m
 * @param response The HttpServletResponse
 * @param e Thrown RestEventApiValidationException
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ModelAndView restEventApiMethodArgumentNotValidExceptionHandler(HttpServletRequest request,
        MethodArgumentNotValidException e) throws Exception {
    RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>();
    Locale userLocale = request.getLocale();
    String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE
            .getDefaultMessageText();

    for (ObjectError globalError : e.getBindingResult().getGlobalErrors()) {
        restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(),
                this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(),
                        descriprionNotAvailableDefaultMessage, userLocale)));
    }

    for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {

        String messageCode = null;
        String defaultMessageText = null;

        if (fieldError.isBindingFailure()) {
            messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode();
            defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText();
        } else {
            //TODO: Find an appropriate way to search pre-defined RestEventAPiError
            messageCode = fieldError.getDefaultMessage();
            defaultMessageText = descriprionNotAvailableDefaultMessage;
        }

        restEventApiStandardResponse
                .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode,
                        fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField()));

    }

    ModelAndView mav = new ModelAndView();
    mav.addObject(restEventApiStandardResponse);
    mav.setView(restEventApiDefaultErrorView);

    return mav;
}

From source file:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java

/**
 * Handle all exceptions of type {@link BindException} thrown by (or passing trough) the Controller's layer
 * //ww  w.  ja v  a  2 s  .c  o  m
 * @param response The HttpServletResponse
 * @param e Thrown RestEventApiValidationException
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView springBindExceptionExceptionHandler(HttpServletRequest request, BindException e)
        throws Exception {

    RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>();
    Locale userLocale = request.getLocale();
    String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE
            .getDefaultMessageText();

    for (ObjectError globalError : e.getGlobalErrors()) {
        restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(),
                this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(),
                        descriprionNotAvailableDefaultMessage, userLocale)));
    }

    for (FieldError fieldError : e.getFieldErrors()) {

        String messageCode = null;
        String defaultMessageText = null;

        if (fieldError.isBindingFailure()) {
            messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode();
            defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText();
        } else {
            //TODO: Find an appropriate way to search pre-defined RestEventAPiError
            messageCode = fieldError.getDefaultMessage();
            defaultMessageText = descriprionNotAvailableDefaultMessage;
        }

        restEventApiStandardResponse
                .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode,
                        fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField()));

    }

    ModelAndView mav = new ModelAndView();
    mav.addObject(restEventApiStandardResponse);
    mav.setView(restEventApiDefaultErrorView);

    return mav;
}

From source file:com.all.backend.web.util.JsonResponseInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    if (modelAndView != null && modelAndView.getViewName() != null
            && !modelAndView.getViewName().endsWith(".jsp")) {
        modelAndView.setView(JSON_VIEW);
    }//from  www  .java  2s  . c  om
}

From source file:com.showcase.mobile.BrowseController.java

@RequestMapping("/deletemovie")
public ModelAndView deletemovie(HttpServletRequest servletRequest) {
    logger.info("deletemovie ...");
    ModelAndView mav = new ModelAndView();

    BigInteger id = new BigInteger(servletRequest.getParameter("id"));
    logger.info("id = " + id);
    movieService.deleteMovie(id);// w  w w .  java  2  s  .c o  m

    logger.info("deletemovie sucess ... redirect to browse... ");
    mav.setView(new RedirectView("browse.htm"));
    return mav;
}

From source file:com.showcase.mobile.BrowseController.java

@RequestMapping("/deletefeed")
public ModelAndView deletefeed(HttpServletRequest servletRequest) {
    logger.info("deletefeed ...");
    ModelAndView mav = new ModelAndView();

    BigInteger id = new BigInteger(servletRequest.getParameter("id"));
    logger.info("id = " + id);
    movieService.deleteFeedback(id);/*from w  w w .j av a  2 s .  c  o  m*/

    logger.info("deletefeed sucess ... redirect to viewfeeds... ");
    mav.setView(new RedirectView("viewfeeds.htm"));
    return mav;
}

From source file:com.mmj.app.web.controller.BaseController.java

protected ModelAndView createJsonMav(String code, String msg, Object object) {
    ModelAndView mav = new ModelAndView();
    MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
    mappingJackson2JsonView.getObjectMapper().setSerializationInclusion(Include.NON_NULL);
    mav.setView(mappingJackson2JsonView);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", code);
    map.put("message", msg);
    map.put("data", object);
    mav.addObject("result", map);
    return mav;/*from w  ww  .j a  va 2 s  .c o  m*/
}

From source file:org.centralperf.controller.ApiController.java

/**
 * Get run results as an Excel document (XSLX)
 * The file name for now is centralperf.xlsx
 * @param mav   ModelAndView will be used to return an Excel view
 * @param projectId ID of the project (from URI)
 * @param runId ID of the run (from URI)
 * @return A view that will be resolved as an Excel view by the view resolver
 *///  www. j  av  a  2  s  .c  om
@RequestMapping(value = { "/project/{projectId}/run/{runId}/centralperf.xlsx",
        "/api/getRunResultsHTML/{rundId}/centralperf.xlsx" }, method = RequestMethod.GET)
public ModelAndView getRunResultsAsExcel(ModelAndView mav, @PathVariable("runId") Long runId) {
    Run run = runRepository.findOne(runId);

    // get the view and setup
    ExcelOOXMLView excelView = applicationContext.getBean(ExcelOOXMLView.class);
    excelView.setUrl("/WEB-INF/views/xlsx/centralperf_template");
    mav.getModel().put("run", run);
    mav.setView(excelView);
    // return a view which will be resolved by an excel view resolver
    return mav;
}

From source file:ru.org.linux.user.UserEventController.java

@RequestMapping(value = "/show-replies.jsp", method = RequestMethod.GET)
public ModelAndView showReplies(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "nick", required = false) String nick,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @ModelAttribute("notifications") Action action) throws Exception {
    Template tmpl = Template.getTemplate(request);
    boolean feedRequested = request.getParameterMap().containsKey("output");

    if (nick == null) {
        if (tmpl.isSessionAuthorized()) {
            return new ModelAndView(new RedirectView("/notifications"));
        }// w w w . j a  v  a 2  s. c  o m
        throw new AccessViolationException("not authorized");
    } else {
        User.checkNick(nick);
        if (!tmpl.isSessionAuthorized() && !feedRequested) {
            throw new AccessViolationException("not authorized");
        }
        if (tmpl.isSessionAuthorized() && nick.equals(tmpl.getCurrentUser().getNick()) && !feedRequested) {
            return new ModelAndView(new RedirectView("/notifications"));
        }
        if (!feedRequested && !tmpl.isModeratorSession()) {
            throw new AccessViolationException(
                    "? ?  ?");
        }
    }

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();
    if (feedRequested) {
        topics = 50;
    }

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);

    User user = userDao.getUser(nick);

    boolean showPrivate = tmpl.isModeratorSession();

    User currentUser = tmpl.getCurrentUser();
    params.put("currentUser", currentUser);

    if (currentUser != null && currentUser.getId() == user.getId()) {
        showPrivate = true;
        params.put("unreadCount", user.getUnreadEvents());
        response.addHeader("Cache-Control", "no-cache");
    }

    List<UserEvent> list = userEventService.getRepliesForUser(user, showPrivate, topics, offset,
            UserEventFilterEnum.ALL);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, feedRequested, request.isSecure());

    params.put("isMyNotifications", false);
    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    ModelAndView result = new ModelAndView("show-replies", params);

    if (feedRequested) {
        result.addObject("feed-type", "rss");
        if ("atom".equals(request.getParameter("output"))) {
            result.addObject("feed-type", "atom");
        }
        result.setView(feedView);
    }
    return result;
}

From source file:com.showcase.mobile.BrowseController.java

@RequestMapping("/savefeed")
public ModelAndView savefeed(HttpServletRequest servletRequest) {
    logger.info("savefeed ...");
    ModelAndView mav = new ModelAndView();

    String username = servletRequest.getParameter("username");
    String email = servletRequest.getParameter("email");
    String comments = servletRequest.getParameter("comments");

    Feedback feed = new Feedback(username, email, comments);

    movieService.saveFeed(feed);//from w  ww  . j  a  v a 2  s.co m

    logger.info("savefeed sucess ... redirect to browse... ");
    mav.setView(new RedirectView("viewfeeds.htm"));
    return mav;
}

From source file:org.openmrs.module.vcttrac.web.controller.VCTPreRegistrationCheckupController.java

/**
 * @see org.springframework.web.servlet.mvc.ParameterizableViewController#handleRequestInternal(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from w ww  .  j av  a2  s  .c  o  m*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //check if the user is logged in
    if (Context.getAuthenticatedUser() == null) {
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                ContextProvider.getMessage("require.login"));
        return new ModelAndView(new RedirectView(request.getContextPath() + "/login.htm"));
    }

    ModelAndView mav = new ModelAndView();
    VCTModuleService vms = Context.getService(VCTModuleService.class);

    //initially the client doesn't exists in the database
    boolean found = false;

    //if the type of counseling has not been specified, redirect to home page to start over
    if (request.getParameter("type") == null) {
        mav.setView(new RedirectView("vctHome.htm"));
        log.info(
                ">>>VCT>>PRE>>REGISTRATION>>CHECKUP>>CONTROLLER>> Type of counseling has not been specified, redirect to home page...");
        return mav;
    } else
        mav.setViewName(getViewName());

    //load utilities
    loadUtils(mav);

    if (request.getParameter("type") != null) {
        Integer pId = null;//patientId

        //attempting to find client using nid
        if (request.getParameter("nid") != null && request.getParameter("nid").trim().compareTo("") != 0) {

            Integer cId = vms.getPersonIdByNID(request.getParameter("nid"));//clientId

            //if the client is found, change found = true and set the pId to the one corresponding to the person
            if (cId != null) {
                found = true;
                pId = cId;
            }

            //redict the view accordingly
            if (request.getParameter("type").trim().compareToIgnoreCase("vct") == 0)
                mav.setView(new RedirectView("vctRegistration.form?type=vct&select="
                        + (((found)) ? ("choose&clientId=" + pId) : "new")));
            else
                mav.setView(new RedirectView("vctRegistration.form?type=pit&select="
                        + (((found)) ? ("choose&clientId=" + pId) : "new")));

            //pack the nid in the model object
            mav.addObject("nid", request.getParameter("nid"));
        } else if (request.getParameter("idType") != null
                && request.getParameter("idType").trim().compareTo("") != 0) {

            List<PatientIdentifierType> identifierTypes = new ArrayList<PatientIdentifierType>();
            identifierTypes.add(Context.getPatientService()
                    .getPatientIdentifierType(Integer.valueOf(request.getParameter("idType"))));

            List<Location> identifierLocs = new ArrayList<Location>();
            identifierLocs.add(Context.getLocationService()
                    .getLocation(Integer.valueOf(request.getParameter("identifierLocation"))));

            List<PatientIdentifier> piList = Context.getPatientService().getPatientIdentifiers(
                    request.getParameter("ptIdentifier"), identifierTypes, identifierLocs, null, null);

            if (piList != null && piList.size() > 0) {

                found = true;
                pId = piList.get(0).getPatient().getPersonId();

                // check for an existing NID for this client
                identifierTypes = new ArrayList<PatientIdentifierType>();
                identifierTypes.add(Context.getPatientService()
                        .getPatientIdentifierType(VCTConfigurationUtil.getNIDIdentifierTypeId()));

                List<Patient> patients = new ArrayList<Patient>();
                patients.add(piList.get(0).getPatient());

                piList = Context.getPatientService().getPatientIdentifiers(null, identifierTypes, null,
                        patients, null);

                if (piList != null && piList.size() > 0) {
                    found = true;
                    mav.addObject("nid", piList.get(0).getIdentifier());
                } else
                    mav.addObject("nid", request.getParameter("nid"));

            }

            //redict the view accordingly
            if (request.getParameter("type").trim().compareToIgnoreCase("vct") == 0)
                mav.setView(new RedirectView("vctRegistration.form?type=vct&select="
                        + (((found)) ? ("choose&clientId=" + pId) : "new")));
            else
                mav.setView(new RedirectView("vctRegistration.form?type=pit&select="
                        + (((found)) ? ("choose&clientId=" + pId) : "new")));
        }
    }
    return mav;
}