Java Code Examples for org.springframework.web.servlet.support.RequestContextUtils#getLocale()

The following examples show how to use org.springframework.web.servlet.support.RequestContextUtils#getLocale() . 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: CargoTrackingController.java    From dddsample-core with MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
protected String onSubmit(final HttpServletRequest request,
                                                         final TrackCommand command,
                                                         final Map<String, Object> model,
                                                         final BindingResult bindingResult) {
    new TrackCommandValidator().validate(command, bindingResult);

    final TrackingId trackingId = new TrackingId(command.getTrackingId());
    final Cargo cargo = cargoRepository.find(trackingId);

    if (cargo != null) {
        final Locale locale = RequestContextUtils.getLocale(request);
        final List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
        model.put("cargo", new CargoTrackingViewAdapter(cargo, messageSource, locale, handlingEvents));
    } else {
        bindingResult.rejectValue("trackingId", "cargo.unknown_id", new Object[]{command.getTrackingId()}, "Unknown tracking id");
    }
    return "track";
}
 
Example 2
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 3
Source File: AbstractRestExceptionHandler.java    From kaif with Apache License 2.0 5 votes vote down vote up
private Locale resolveLocale(WebRequest request) {
  if (!(request instanceof ServletWebRequest)) {
    return request.getLocale();
  }
  ServletWebRequest servletWebRequest = (ServletWebRequest) request;
  return RequestContextUtils.getLocale(servletWebRequest.getRequest());
}
 
Example 4
Source File: AbstractExcelView.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
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);
	}
	//POIFSFileSystem fs = new POIFSFileSystem(inputFile.getInputStream());
	return new XSSFWorkbook(inputFile.getInputStream());
}
 
Example 5
Source File: TilesView.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a Tiles {@link Request}.
 * <p>This implementation creates a {@link ServletRequest}.
 * @param request the current request
 * @param response the current response
 * @return the Tiles request
 */
protected Request createTilesRequest(final HttpServletRequest request, HttpServletResponse response) {
	return new ServletRequest(this.applicationContext, request, response) {
		@Override
		public Locale getRequestLocale() {
			return RequestContextUtils.getLocale(request);
		}
	};
}
 
Example 6
Source File: AbstractJExcelView.java    From spring4-understanding with Apache License 2.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 7
Source File: TilesView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Tiles {@link Request}.
 * <p>This implementation creates a {@link ServletRequest}.
 * @param request the current request
 * @param response the current response
 * @return the Tiles request
 */
protected Request createTilesRequest(final HttpServletRequest request, HttpServletResponse response) {
	return new ServletRequest(this.applicationContext, request, response) {
		@Override
		public Locale getRequestLocale() {
			return RequestContextUtils.getLocale(request);
		}
	};
}
 
Example 8
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 9
Source File: AbstractJExcelView2.java    From JDeSurvey with GNU Affero General Public License v3.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 10
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);
}
 
Example 11
Source File: AbstractExcelView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Creates 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 HSSFWorkbook
 * @throws Exception in case of failure
 */
protected HSSFWorkbook 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 new HSSFWorkbook(inputFile.getInputStream());
}
 
Example 12
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 13
Source File: FormatBytesTag.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public int doEndTag() throws JspException {
    Locale locale = RequestContextUtils.getLocale((HttpServletRequest) pageContext.getRequest());
    String result = StringUtil.formatBytes(bytes, locale);

    try {
        pageContext.getOut().print(result);
    } catch (IOException x) {
        throw new JspTagException(x);
    }
    return EVAL_PAGE;
}
 
Example 14
Source File: BaseApi.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
/**
 * 获取国际化提示信息  ?lang=en_US / zh_CN
 */
protected String getI18nMessage(HttpServletRequest request, String messageKey) {
    Locale locale = RequestContextUtils.getLocale(request);
    return messageSource.getMessage(messageKey, null, locale);
}
 
Example 15
Source File: DispatcherServletWebRequest.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Locale getLocale() {
	return RequestContextUtils.getLocale(getRequest());
}
 
Example 16
Source File: DispatcherServletWebRequest.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Locale getLocale() {
	return RequestContextUtils.getLocale(getRequest());
}
 
Example 17
Source File: VelocityView.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Locale getLocale() {
	return RequestContextUtils.getLocale(this.request);
}
 
Example 18
Source File: AnnotationMethodHandlerExceptionResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest},
 * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal},
 * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream},
 * response {@link Writer}, and the given {@code thrownException}.
 * @param parameterType the method parameter type
 * @param webRequest the request
 * @param thrownException the exception thrown
 * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED}
 */
protected Object resolveStandardArgument(Class<?> parameterType, NativeWebRequest webRequest,
		Exception thrownException) throws Exception {

	if (parameterType.isInstance(thrownException)) {
		return thrownException;
	}
	else if (WebRequest.class.isAssignableFrom(parameterType)) {
		return webRequest;
	}

	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

	if (ServletRequest.class.isAssignableFrom(parameterType)) {
		return request;
	}
	else if (ServletResponse.class.isAssignableFrom(parameterType)) {
		return response;
	}
	else if (HttpSession.class.isAssignableFrom(parameterType)) {
		return request.getSession();
	}
	else if (Principal.class.isAssignableFrom(parameterType)) {
		return request.getUserPrincipal();
	}
	else if (Locale.class == parameterType) {
		return RequestContextUtils.getLocale(request);
	}
	else if (InputStream.class.isAssignableFrom(parameterType)) {
		return request.getInputStream();
	}
	else if (Reader.class.isAssignableFrom(parameterType)) {
		return request.getReader();
	}
	else if (OutputStream.class.isAssignableFrom(parameterType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(parameterType)) {
		return response.getWriter();
	}
	else {
		return WebArgumentResolver.UNRESOLVED;

	}
}
 
Example 19
Source File: AnnotationMethodHandlerExceptionResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest},
 * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal},
 * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream},
 * response {@link Writer}, and the given {@code thrownException}.
 * @param parameterType the method parameter type
 * @param webRequest the request
 * @param thrownException the exception thrown
 * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED}
 */
protected Object resolveStandardArgument(Class<?> parameterType, NativeWebRequest webRequest,
		Exception thrownException) throws Exception {

	if (parameterType.isInstance(thrownException)) {
		return thrownException;
	}
	else if (WebRequest.class.isAssignableFrom(parameterType)) {
		return webRequest;
	}

	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

	if (ServletRequest.class.isAssignableFrom(parameterType)) {
		return request;
	}
	else if (ServletResponse.class.isAssignableFrom(parameterType)) {
		return response;
	}
	else if (HttpSession.class.isAssignableFrom(parameterType)) {
		return request.getSession();
	}
	else if (Principal.class.isAssignableFrom(parameterType)) {
		return request.getUserPrincipal();
	}
	else if (Locale.class == parameterType) {
		return RequestContextUtils.getLocale(request);
	}
	else if (InputStream.class.isAssignableFrom(parameterType)) {
		return request.getInputStream();
	}
	else if (Reader.class.isAssignableFrom(parameterType)) {
		return request.getReader();
	}
	else if (OutputStream.class.isAssignableFrom(parameterType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(parameterType)) {
		return response.getWriter();
	}
	else {
		return WebArgumentResolver.UNRESOLVED;

	}
}
 
Example 20
Source File: FreeMarkerView.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Render the FreeMarker view to the given response, using the given model
 * map which contains the complete template model to use.
 * <p>The default implementation renders the template specified by the "url"
 * bean property, retrieved via {@code getTemplate}. It delegates to the
 * {@code processTemplate} method to merge the template instance with
 * the given template model.
 * <p>Adds the standard Freemarker hash models to the model: request parameters,
 * request, session and application (ServletContext), as well as the JSP tag
 * library hash model.
 * <p>Can be overridden to customize the behavior, for example to render
 * multiple templates into a single view.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @throws IOException if the template file could not be retrieved
 * @throws Exception if rendering failed
 * @see #setUrl
 * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
 * @see #getTemplate(java.util.Locale)
 * @see #processTemplate
 * @see freemarker.ext.servlet.FreemarkerServlet
 */
protected void doRender(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	// Expose model to JSP tags (as request attributes).
	exposeModelAsRequestAttributes(model, request);
	// Expose all standard FreeMarker hash models.
	SimpleHash fmModel = buildTemplateModel(model, request, response);

	// Grab the locale-specific version of the template.
	Locale locale = RequestContextUtils.getLocale(request);
	processTemplate(getTemplate(locale), fmModel, response);
}