org.springframework.web.servlet.support.RequestContextUtils Java Examples

The following examples show how to use org.springframework.web.servlet.support.RequestContextUtils. 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
Source File: HelloController.java    From springboot-learn with MIT License 6 votes vote down vote up
@GetMapping(value = "/message")
@ResponseBody
public String message(HttpServletRequest request) {
    //获取当前的本地区域信息
    Locale locale = LocaleContextHolder.getLocale();
    //或者
    Locale locale1 = RequestContextUtils.getLocale(request);

    Locale aDefault = Locale.getDefault();

    //不能使用Locale.ENGLISH
    Locale english = Locale.US;
    //不能Locale.CHINESE
    Locale chinese = Locale.CHINA;

    //其中第二个参数为占位符数据
    String welcome = messageSource.getMessage("welcome", null, english);
    String hello = messageSource.getMessage("hello", new String[]{"i18n"}, english);

    String welcome1 = messagesUtil.getMessage("welcome", chinese);
    String hello1 = messagesUtil.getMessage("hello", new String[]{"i18n"}, chinese);
    System.out.println(hello1 + welcome1);

    return hello + welcome;
}
 
Example #2
Source File: RedirectView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find the registered {@link RequestDataValueProcessor}, if any, and allow
 * it to update the redirect target URL.
 * @param targetUrl the given redirect URL
 * @return the updated URL or the same as URL as the one passed in
 */
protected String updateTargetUrl(String targetUrl, Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) {

	WebApplicationContext wac = getWebApplicationContext();
	if (wac == null) {
		wac = RequestContextUtils.findWebApplicationContext(request, getServletContext());
	}

	if (wac != null && wac.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
		RequestDataValueProcessor processor = wac.getBean(
				RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
		return processor.processUrl(request, targetUrl);
	}

	return targetUrl;
}
 
Example #3
Source File: CategoryRestController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/categories/{id}", method=RequestMethod.POST)
public @ResponseBody DomainObjectUpdatedModel update(
		@Valid CategoryEditForm form,
		BindingResult result,
		@PathVariable long id,
		AuthorizedUser authorizedUser,
		HttpServletRequest request,
		HttpServletResponse response) throws BindException {
	form.setId(id);
	if (result.hasErrors()) {
		throw new BindException(result);
	}
	Category category = categoryService.updateCategory(form.buildCategoryUpdateRequest(), authorizedUser);
	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	flashMap.put("updatedCategory", category);
	RequestContextUtils.getFlashMapManager(request).saveOutputFlashMap(flashMap, request, response);
	return new DomainObjectUpdatedModel<>(category);
}
 
Example #4
Source File: RedirectView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Convert model to request parameters and redirect to the given URL.
 * @see #appendQueryProperties
 * @see #sendRedirect
 */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws IOException {

	String targetUrl = createTargetUrl(model, request);
	targetUrl = updateTargetUrl(targetUrl, model, request, response);

	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	if (!CollectionUtils.isEmpty(flashMap)) {
		UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build();
		flashMap.setTargetRequestPath(uriComponents.getPath());
		flashMap.addTargetRequestParams(uriComponents.getQueryParams());
		FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
		if (flashMapManager == null) {
			throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set");
		}
		flashMapManager.saveOutputFlashMap(flashMap, request, response);
	}

	sendRedirect(request, response, targetUrl, this.http10Compatible);
}
 
Example #5
Source File: RequestMappingHandlerAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
		ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {

	modelFactory.updateModel(webRequest, mavContainer);
	if (mavContainer.isRequestHandled()) {
		return null;
	}
	ModelMap model = mavContainer.getModel();
	ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model);
	if (!mavContainer.isViewReference()) {
		mav.setView((View) mavContainer.getView());
	}
	if (model instanceof RedirectAttributes) {
		Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
	}
	return mav;
}
 
Example #6
Source File: PrintingResultHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Print {@link MvcResult} details.
 */
@Override
public final void handle(MvcResult result) throws Exception {
	this.printer.printHeading("MockHttpServletRequest");
	printRequest(result.getRequest());

	this.printer.printHeading("Handler");
	printHandler(result.getHandler(), result.getInterceptors());

	this.printer.printHeading("Async");
	printAsyncResult(result);

	this.printer.printHeading("Resolved Exception");
	printResolvedException(result.getResolvedException());

	this.printer.printHeading("ModelAndView");
	printModelAndView(result.getModelAndView());

	this.printer.printHeading("FlashMap");
	printFlashMap(RequestContextUtils.getOutputFlashMap(result.getRequest()));

	this.printer.printHeading("MockHttpServletResponse");
	printResponse(result.getResponse());
}
 
Example #7
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void saveFlashAttributes(ModelAndViewContainer mav, NativeWebRequest request, String location) {
	mav.setRedirectModelScenario(true);
	ModelMap model = mav.getModel();
	if (model instanceof RedirectAttributes) {
		Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
		if (!CollectionUtils.isEmpty(flashAttributes)) {
			HttpServletRequest req = request.getNativeRequest(HttpServletRequest.class);
			HttpServletResponse res = request.getNativeResponse(HttpServletResponse.class);
			if (req != null) {
				RequestContextUtils.getOutputFlashMap(req).putAll(flashAttributes);
				if (res != null) {
					RequestContextUtils.saveOutputFlashMap(location, req, res);
				}
			}
		}
	}
}
 
Example #8
Source File: RequestMappingHandlerAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
		ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {

	modelFactory.updateModel(webRequest, mavContainer);
	if (mavContainer.isRequestHandled()) {
		return null;
	}
	ModelMap model = mavContainer.getModel();
	ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
	if (!mavContainer.isViewReference()) {
		mav.setView((View) mavContainer.getView());
	}
	if (model instanceof RedirectAttributes) {
		Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
	}
	return mav;
}
 
Example #9
Source File: RedirectView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Find the registered {@link RequestDataValueProcessor}, if any, and allow
 * it to update the redirect target URL.
 * @param targetUrl the given redirect URL
 * @return the updated URL or the same as URL as the one passed in
 */
protected String updateTargetUrl(String targetUrl, Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) {

	WebApplicationContext wac = getWebApplicationContext();
	if (wac == null) {
		wac = RequestContextUtils.findWebApplicationContext(request, getServletContext());
	}

	if (wac != null && wac.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
		RequestDataValueProcessor processor = wac.getBean(
				RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
		return processor.processUrl(request, targetUrl);
	}

	return targetUrl;
}
 
Example #10
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void saveFlashAttributes(ModelAndViewContainer mav, NativeWebRequest request, String location) {
	mav.setRedirectModelScenario(true);
	ModelMap model = mav.getModel();
	if (model instanceof RedirectAttributes) {
		Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
		if (!CollectionUtils.isEmpty(flashAttributes)) {
			HttpServletRequest req = request.getNativeRequest(HttpServletRequest.class);
			HttpServletResponse res = request.getNativeResponse(HttpServletResponse.class);
			if (req != null) {
				RequestContextUtils.getOutputFlashMap(req).putAll(flashAttributes);
				if (res != null) {
					RequestContextUtils.saveOutputFlashMap(location, req, res);
				}
			}
		}
	}
}
 
Example #11
Source File: PrintingResultHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Print {@link MvcResult} details.
 */
@Override
public final void handle(MvcResult result) throws Exception {
	this.printer.printHeading("MockHttpServletRequest");
	printRequest(result.getRequest());

	this.printer.printHeading("Handler");
	printHandler(result.getHandler(), result.getInterceptors());

	this.printer.printHeading("Async");
	printAsyncResult(result);

	this.printer.printHeading("Resolved Exception");
	printResolvedException(result.getResolvedException());

	this.printer.printHeading("ModelAndView");
	printModelAndView(result.getModelAndView());

	this.printer.printHeading("FlashMap");
	printFlashMap(RequestContextUtils.getOutputFlashMap(result.getRequest()));

	this.printer.printHeading("MockHttpServletResponse");
	printResponse(result.getResponse());
}
 
Example #12
Source File: RedirectView.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find the registered {@link RequestDataValueProcessor}, if any, and allow
 * it to update the redirect target URL.
 * @param targetUrl the given redirect URL
 * @return the updated URL or the same as URL as the one passed in
 */
protected String updateTargetUrl(String targetUrl, Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) {

	WebApplicationContext wac = getWebApplicationContext();
	if (wac == null) {
		wac = RequestContextUtils.findWebApplicationContext(request, getServletContext());
	}

	if (wac != null && wac.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
		RequestDataValueProcessor processor = wac.getBean(
				RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
		return processor.processUrl(request, targetUrl);
	}

	return targetUrl;
}
 
Example #13
Source File: CategoryRestController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/categories", method=RequestMethod.POST)
public @ResponseBody DomainObjectSavedModel save(
		@Valid CategoryCreateForm form,
		BindingResult result,
		AuthorizedUser authorizedUser,
		HttpServletRequest request,
		HttpServletResponse response) throws BindException {
	if (result.hasErrors()) {
		throw new BindException(result);
	}
	Category category = categoryService.createCategory(form.buildCategoryCreateRequest(), authorizedUser);
	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	flashMap.put("savedCategory", category);
	RequestContextUtils.getFlashMapManager(request).saveOutputFlashMap(flashMap, request, response);
	return new DomainObjectSavedModel<>(category);
}
 
Example #14
Source File: MessageResolver.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获得国际化信息
 * 
 * @param request
 *            HttpServletRequest
 * @param code
 *            国际化代码
 * @param args
 *            替换参数
 * @return
 * @see org.springframework.context.MessageSource#getMessage(String,
 *      Object[], Locale)
 */
public static String getMessage(HttpServletRequest request, String code,
		Object... args) {
	WebApplicationContext messageSource = RequestContextUtils
			.getWebApplicationContext(request);
	if (messageSource == null) {
		throw new IllegalStateException("WebApplicationContext not found!");
	}
	LocaleResolver localeResolver = RequestContextUtils
			.getLocaleResolver(request);
	Locale locale;
	if (localeResolver != null) {
		locale = localeResolver.resolveLocale(request);
	} else {
		locale = request.getLocale();
	}
	return messageSource.getMessage(code, args, locale);
}
 
Example #15
Source File: AbstractHtmlElementTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected MockPageContext createAndPopulatePageContext() throws JspException {
	MockPageContext pageContext = createPageContext();
	MockHttpServletRequest request = (MockHttpServletRequest) pageContext.getRequest();
	((StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request))
			.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
	extendRequest(request);
	extendPageContext(pageContext);
	RequestContext requestContext = new JspAwareRequestContext(pageContext);
	pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, requestContext);
	return pageContext;
}
 
Example #16
Source File: SimpleWebApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	if (!(RequestContextUtils.findWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
		throw new ServletException("Incorrect WebApplicationContext");
	}
	if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {
		throw new ServletException("Incorrect LocaleResolver");
	}
	if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
		throw new ServletException("Incorrect Locale");
	}
	return null;
}
 
Example #17
Source File: CategoryRestController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/{language}/categories/{id}", method= RequestMethod.DELETE)
public @ResponseBody DomainObjectDeletedModel<Long> delete(
		@PathVariable String language,
		@PathVariable long id,
		AuthorizedUser authorizedUser,
		HttpServletRequest request,
		HttpServletResponse response) throws BindException {
	Category category = categoryService.deleteCategory(id, language);
	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	flashMap.put("deletedCategory", category);
	RequestContextUtils.getFlashMapManager(request).saveOutputFlashMap(flashMap, request, response);
	return new DomainObjectDeletedModel<>(category);
}
 
Example #18
Source File: AbstractHtmlElementTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
	RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
	HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
	WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
	wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
	return mockProcessor;
}
 
Example #19
Source File: ThemeChangeInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws ServletException {

	String newTheme = request.getParameter(this.paramName);
	if (newTheme != null) {
		ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
		if (themeResolver == null) {
			throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
		}
		themeResolver.setThemeName(request, response, newTheme);
	}
	// Proceed in any case.
	return true;
}
 
Example #20
Source File: LocaleChangeInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws ServletException {

	String newLocale = request.getParameter(getParamName());
	if (newLocale != null) {
		if (checkHttpMethod(request.getMethod())) {
			LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
			if (localeResolver == null) {
				throw new IllegalStateException(
						"No LocaleResolver found: not in a DispatcherServlet request?");
			}
			try {
				localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
			}
			catch (IllegalArgumentException ex) {
				if (isIgnoreInvalidLocale()) {
					logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + ex.getMessage());
				}
				else {
					throw ex;
				}
			}
		}
	}
	// Proceed in any case.
	return true;
}
 
Example #21
Source File: AbstractJExcelView.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create the workbook from an existing XLS document.
 * @param url the URL of the Excel template without localization part nor extension
 * @param request current HTTP request
 * @return the template workbook
 * @throws Exception in case of failure
 */
protected Workbook getTemplateSource(String url, HttpServletRequest request) throws Exception {
	LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext());
	Locale userLocale = RequestContextUtils.getLocale(request);
	Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale);

	// Create the Excel document from the source.
	if (logger.isDebugEnabled()) {
		logger.debug("Loading Excel workbook from " + inputFile);
	}
	return Workbook.getWorkbook(inputFile.getInputStream());
}
 
Example #22
Source File: SimpleWebApplicationContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
		throw new ServletException("Incorrect WebApplicationContext");
	}
	if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {
		throw new ServletException("Incorrect LocaleResolver");
	}
	if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
		throw new ServletException("Incorrect Locale");
	}
	return null;
}
 
Example #23
Source File: PlayQueueService.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
private List<PlayQueueInfo.Entry> convertMediaFileList(HttpServletRequest request, Player player) {

        String url = NetworkService.getBaseUrl(request);
        Locale locale = RequestContextUtils.getLocale(request);
        PlayQueue playQueue = player.getPlayQueue();

        List<PlayQueueInfo.Entry> entries = new ArrayList<>();
        for (MediaFile file : playQueue.getFiles()) {

            String albumUrl = url + "main.view?id=" + file.getId();
            String streamUrl = url + "stream?player=" + player.getId() + "&id=" + file.getId();
            String coverArtUrl = url + "coverArt.view?id=" + file.getId();

            String remoteStreamUrl = jwtSecurityService.addJWTToken(url + "ext/stream?player=" + player.getId() + "&id=" + file.getId());
            String remoteCoverArtUrl = jwtSecurityService.addJWTToken(url + "ext/coverArt.view?id=" + file.getId());

            String format = formatFormat(player, file);
            String username = securityService.getCurrentUsername(request);
            boolean starred = mediaFileService.getMediaFileStarredDate(file.getId(), username) != null;
            entries.add(new PlayQueueInfo.Entry(file.getId(), file.getTrackNumber(), file.getTitle(), file.getArtist(),
                    file.getAlbumName(), file.getGenre(), file.getYear(), formatBitRate(file),
                    file.getDurationSeconds(), file.getDurationString(), format, formatContentType(format),
                    formatFileSize(file.getFileSize(), locale), starred, albumUrl, streamUrl, remoteStreamUrl,
                    coverArtUrl, remoteCoverArtUrl));
        }

        return entries;
    }
 
Example #24
Source File: AbstractUrlViewController.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Retrieves the URL path to use for lookup and delegates to
 * {@link #getViewNameForRequest}. Also adds the content of
 * {@link RequestContextUtils#getInputFlashMap} to the model.
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
	String viewName = getViewNameForRequest(request);
	if (logger.isTraceEnabled()) {
		logger.trace("Returning view name '" + viewName + "'");
	}
	return new ModelAndView(viewName, RequestContextUtils.getInputFlashMap(request));
}
 
Example #25
Source File: StatusController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> map = new HashMap<>();

    List<TransferStatus> streamStatuses = statusService.getAllStreamStatuses();
    List<TransferStatus> downloadStatuses = statusService.getAllDownloadStatuses();
    List<TransferStatus> uploadStatuses = statusService.getAllUploadStatuses();

    Locale locale = RequestContextUtils.getLocale(request);
    List<TransferStatusHolder> transferStatuses = new ArrayList<>();

    for (int i = 0; i < streamStatuses.size(); i++) {
        long minutesAgo = streamStatuses.get(i).getMillisSinceLastUpdate() / 1000L / 60L;
        if (minutesAgo < 60L) {
            transferStatuses.add(new TransferStatusHolder(streamStatuses.get(i), true, false, false, i, locale));
        }
    }
    for (int i = 0; i < downloadStatuses.size(); i++) {
        transferStatuses.add(new TransferStatusHolder(downloadStatuses.get(i), false, true, false, i, locale));
    }
    for (int i = 0; i < uploadStatuses.size(); i++) {
        transferStatuses.add(new TransferStatusHolder(uploadStatuses.get(i), false, false, true, i, locale));
    }

    map.put("transferStatuses", transferStatuses);
    map.put("chartWidth", StatusChartController.IMAGE_WIDTH);
    map.put("chartHeight", StatusChartController.IMAGE_HEIGHT);

    return new ModelAndView("status","model",map);
}
 
Example #26
Source File: MessageContext.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * インフォメーション・メッセージをフラッシュ・スコープにストアします。
 * @param code メッセージ・コード
 * @param replace メッセージのプレースホルダを置換するキーとバリューの{@link Map}
 */
public void saveInformationMessageToFlash(
        String code,
        Map<String, ? extends Object> replace) {
    Args.checkNotNull(code);
    Messages messages = (Messages)RequestContextUtils.getOutputFlashMap(request).get(INFORMATION_MESSAGE_KEY_TO_FLASH);
    if (messages == null) {
        messages = new Messages(MessageType.INFORMATION);
        RequestContextUtils.getOutputFlashMap(request).put(INFORMATION_MESSAGE_KEY_TO_FLASH, messages);
    }
    messages.add(new Message(code, replace));
}
 
Example #27
Source File: MessageTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void nullMessageSource() throws JspException {
	PageContext pc = createPageContext();
	ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
			RequestContextUtils.findWebApplicationContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	ctx.close();

	MessageTag tag = new MessageTag();
	tag.setPageContext(pc);
	tag.setCode("test");
	tag.setVar("testvar2");
	tag.doStartTag();
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
}
 
Example #28
Source File: JseErrorsTagTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void インフォメーションメッセージがフラッシュスコープにセットされ出力されない() throws Exception {

    MessageContext context = new MessageContext(request);
    context.saveInformationMessageToFlash("I-JX_INFORMATIONS_TAG_TEST#0001");
    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
    request.setAttribute(MessageContext.INFORMATION_MESSAGE_KEY_TO_FLASH, flashMap.get(MessageContext.INFORMATION_MESSAGE_KEY_TO_FLASH));
    JseErrorsTag tag = new JseErrorsTag();
    tag.setJspContext(page);
    tag.doTag();

    assertThat(response.getContentAsString(), is(""));
}
 
Example #29
Source File: AbstractHtmlElementTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
	RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
	ServletRequest request = getPageContext().getRequest();
	StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.getWebApplicationContext(request);
	wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
	return mockProcessor;
}
 
Example #30
Source File: SpringLocaleResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Locale resolveLocale(Request request) {
	try {
		HttpServletRequest servletRequest = ServletUtil.getServletRequest(request).getRequest();
		if (servletRequest != null) {
			return RequestContextUtils.getLocale(servletRequest);
		}
	}
	catch (NotAServletEnvironmentException e) {
		// Ignore
	}
	return super.resolveLocale(request);
}