Java Code Examples for org.springframework.web.servlet.ModelAndView#getModelMap()

The following examples show how to use org.springframework.web.servlet.ModelAndView#getModelMap() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 入力エラーを画面オブジェクトに設定する
 * 
 * @param modelAndView
 */
protected void retainValidateErrors(ModelAndView modelAndView) {
    val model = modelAndView.getModelMap();

    if (model != null && model.containsAttribute(MAV_ERRORS)) {
        val errors = model.get(MAV_ERRORS);

        if (errors != null && errors instanceof BeanPropertyBindingResult) {
            val br = ((BeanPropertyBindingResult) errors);

            if (br.hasErrors()) {
                val formName = br.getObjectName();
                val key = BindingResult.MODEL_KEY_PREFIX + formName;
                model.addAttribute(key, errors);
                model.addAttribute(GLOBAL_MESSAGE, MessageUtils.getMessage(VALIDATION_ERROR));
            }
        }
    }
}
 
Example 2
/**
 * After the controller logic is executed, the form is placed into session and the corresponding view
 * is prepared for rendering.
 *
 * {@inheritDoc}
 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    if (request.getAttribute(UifParameters.Attributes.VIEW_LIFECYCLE_COMPLETE) == null) {
        getModelAndViewService().prepareView(request, modelAndView);
    }

    if ((modelAndView != null) && (modelAndView.getModelMap() != null)) {
        Object model = modelAndView.getModelMap().get(UifConstants.DEFAULT_MODEL_NAME);
        if ((model != null) && (model instanceof ViewModel)) {
            ((ViewModel) model).preRender(request);
        }
    }

    ProcessLogger.trace("post-handle");
}
 
Example 3
@SuppressWarnings("unchecked")
@Test
public void testPostHandle() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Object handler = null;
    ModelAndView modelAndView = new ModelAndView();

    Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();

    expect(portalPreferenceService.getPreferencesAsMap()).andReturn(preferenceMap);
    replay(portalPreferenceService);
    interceptor.postHandle(request, response, handler, modelAndView);
    verify(portalPreferenceService);

    Map<String, Object> modelMap = modelAndView.getModelMap();
    assertThat((Map<String, PortalPreference>) modelMap.get(ModelKeys.PORTAL_SETTINGS), sameInstance(preferenceMap));
    assertThat((StaticContentFetcherService) modelMap.get(ModelKeys.STATIC_CONTENT_CACHE), sameInstance(staticContentFetcherService));
}
 
Example 4
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView == null) return;

    if (StringUtils.startsWith(modelAndView.getViewName(), "redirect:")) return;

    ModelMap model = modelAndView.getModelMap();

    model.addAttribute("standby", quartzScheduler.isInStandbyMode());
    model.addAttribute("root", configuration.getRoot());
    String current = request.getServletPath() + request.getPathInfo();
    model.addAttribute("current", URLEncoder.encode(current, "UTF-8"));
    model.addAttribute("utils", utilsTool);
    model.addAttribute("format", formatTool);
    model.addAttribute("version", version);
}
 
Example 5
@GetMapping("download/xls")
public ModelAndView exportXls() {
    ModelAndView modelAndView = new ModelAndView(weatherUserInfoExcelView);
    ExcelExportBO<WeatherVO> exportBO = new ExcelExportBO<>();
    exportBO.setExcelFileName("城市天气情况");
    exportBO.setSheetName("城市天气情况");
    List<WeatherVO> weatherVOList = new ArrayList<>();
    weatherVOList.add(WeatherVO.builder().cityName("北京").weatherDetail("雷阵雨转多云").build());
    weatherVOList.add(WeatherVO.builder().cityName("上海").weatherDetail("多云转晴").build());
    exportBO.setContent(weatherVOList);
    ModelMap modelMap = modelAndView.getModelMap();
    modelMap.put(EXPORT_DATA, exportBO);
    return modelAndView;
}
 
Example 6
@ExceptionHandler(value = Exception.class)
public ResponseEntity<ModelMap> defaultErrorHandler(HttpServletRequest request, Exception e) {
    ModelAndView model = ticket.get(request.getRequestURL().toString(), e);

    return new ResponseEntity<>(model.getModelMap(),
            HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example 7
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView != null) {
        ModelMap map = modelAndView.getModelMap();
        map.addAttribute(ModelKeys.PORTAL_SETTINGS, preferenceService.getPreferencesAsMap());
        map.addAttribute(ModelKeys.STATIC_CONTENT_CACHE, staticContentFetcherService);
    }
    super.postHandle(request, response, handler, modelAndView);
}
 
Example 8
Source Project: dubai   File: AclInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView != null && modelAndView.getModelMap() != null) {
        String currentModuleCode = getCurrentModuleCode(request);
        Module currentModule = moduleService.findByModuleCode(currentModuleCode);
        modelAndView.getModelMap().addAttribute("_currentModuleCode", currentModuleCode);
        modelAndView.getModelMap().addAttribute("_modules", moduleService.loadAllModule());
        modelAndView.getModelMap().addAttribute("_menuGroups", currentModule.getMenuGroups());
    }
}
 
Example 9
@Override
public void postHandle(HttpServletRequest request,
		HttpServletResponse response, Object handler, ModelAndView mav)
		throws Exception {
	CmsUser user = CmsUtils.getUser(request);
	// 不控制权限时perm为null,PermistionDirective标签将以此作为依据不处理权限问题。
	if (auth && user != null && !user.isSuper() && mav != null
			&& mav.getModelMap() != null && mav.getViewName() != null
			&& !mav.getViewName().startsWith("redirect:")) {
		mav.getModelMap().addAttribute(PERMISSION_MODEL, user.getPerms());
	}
}
 
Example 10
Source Project: wallride   File: PagePreviewController.java    License: Apache License 2.0 4 votes vote down vote up
@RequestMapping
public void preview(
		@PathVariable String language,
		@Valid @ModelAttribute("form") PagePreviewForm form,
		BindingResult result,
		AuthorizedUser authorizedUser,
		Model model,
		HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	Page page = new Page();
	page.setLanguage(language);
	page.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
	page.setTitle(form.getTitle());
	page.setBody(form.getBody());
	page.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());
	List<CustomFieldValue> fieldValues = new ArrayList<>();
	for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
		CustomFieldValue value = new CustomFieldValue();
		value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
		if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX) && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
			value.setTextValue(String.join(",", valueForm.getTextValues()));
		} else {
			value.setTextValue(valueForm.getTextValue());
		}
		value.setStringValue(valueForm.getStringValue());
		value.setNumberValue(valueForm.getNumberValue());
		value.setDateValue(valueForm.getDateValue());
		value.setDatetimeValue(valueForm.getDatetimeValue());
		fieldValues.add(value);
	}
	page.setCustomFieldValues(new TreeSet<>(fieldValues));
	page.setAuthor(authorizedUser);

	WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext, "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
	if (context == null) {
		throw new ServiceException("GuestServlet is not ready yet");
	}

	Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
	BlogLanguage blogLanguage = blog.getLanguage(language);
	request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

	DefaultModelAttributeInterceptor interceptor = context.getBean(DefaultModelAttributeInterceptor.class);
	ModelAndView mv = new ModelAndView("dummy");
	interceptor.postHandle(request, response, this, mv);

	final WebContext ctx = new WebContext(
			request,
			response,
			servletContext,
			LocaleContextHolder.getLocale(),
			mv.getModelMap());
	ctx.setVariable("page", page);

	ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
	ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, evaluationContext);

	SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
	String html = templateEngine.process("page/describe", ctx);

	response.setContentType("text/html;charset=UTF-8");
	response.setContentLength(html.getBytes("UTF-8").length);
	response.getWriter().write(html);
}
 
Example 11
@RequestMapping
public void preview(
		@PathVariable String language,
		@Valid @ModelAttribute("form") ArticlePreviewForm form,
		BindingResult result,
		AuthorizedUser authorizedUser,
		Model model,
		HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	Article article = new Article();
	article.setLanguage(language);
	article.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
	article.setTitle(form.getTitle());
	article.setBody(form.getBody());
	article.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());

	List<CustomFieldValue> fieldValues = new ArrayList<>();
	for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
		CustomFieldValue value = new CustomFieldValue();
		value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
		if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX) && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
			value.setTextValue(String.join(",", valueForm.getTextValues()));
		} else {
			value.setTextValue(valueForm.getTextValue());
		}
		value.setStringValue(valueForm.getStringValue());
		value.setNumberValue(valueForm.getNumberValue());
		value.setDateValue(valueForm.getDateValue());
		value.setDatetimeValue(valueForm.getDatetimeValue());
		fieldValues.add(value);
	}
	article.setCustomFieldValues(new TreeSet<>(fieldValues));
	article.setAuthor(authorizedUser);

	WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext, "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
	if (context == null) {
		throw new ServiceException("GuestServlet is not ready yet");
	}

	Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
	BlogLanguage blogLanguage = blog.getLanguage(language);
	request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

	DefaultModelAttributeInterceptor interceptor = context.getBean(DefaultModelAttributeInterceptor.class);
	ModelAndView mv = new ModelAndView("dummy");
	interceptor.postHandle(request, response, this, mv);

	final WebContext ctx = new WebContext(
			request,
			response,
			servletContext,
			LocaleContextHolder.getLocale(),
			mv.getModelMap());
	ctx.setVariable("article", article);

	ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
	ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, evaluationContext);

	SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
	String html = templateEngine.process("article/describe", ctx);

	response.setContentType("text/html;charset=UTF-8");
	response.setContentLength(html.getBytes("UTF-8").length);
	response.getWriter().write(html);
}