Java Code Examples for javax.servlet.http.HttpServletRequest#getLocale()

The following examples show how to use javax.servlet.http.HttpServletRequest#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: AcceptHeaderLocaleResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Locale resolveLocale(HttpServletRequest request) {
	Locale defaultLocale = getDefaultLocale();
	if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
		return defaultLocale;
	}
	Locale requestLocale = request.getLocale();
	List<Locale> supportedLocales = getSupportedLocales();
	if (supportedLocales.isEmpty() || supportedLocales.contains(requestLocale)) {
		return requestLocale;
	}
	Locale supportedLocale = findSupportedLocale(request, supportedLocales);
	if (supportedLocale != null) {
		return supportedLocale;
	}
	return (defaultLocale != null ? defaultLocale : requestLocale);
}
 
Example 2
Source File: MemoryLeakServlet3.java    From easybuggy with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    StringBuilder bodyHtml = new StringBuilder();
    Locale locale = req.getLocale();
    TimeZone tz = TimeZone.getDefault();
    bodyHtml.append("<table class=\"table table-striped table-bordered table-hover\" style=\"font-size:small;\">");
    bodyHtml.append("<tr><td>" + getMsg("label.timezone.id", req.getLocale()) + "</td>");
    bodyHtml.append("<td>" + tz.getID() + "</td></tr>");
    bodyHtml.append("<tr><td>" + getMsg("label.timezone.name", req.getLocale()) + "</td>");
    bodyHtml.append("<td>" + tz.getDisplayName() + "</td></tr>");
    bodyHtml.append("<tr><td>" + getMsg("label.timezone.offset", req.getLocale()) + "</td>");
    bodyHtml.append("<td>" + tz.getRawOffset() + "</td></tr>");
    bodyHtml.append("</table>");
    try {
        toDoRemove();
        
        bodyHtml.append(getInfoMsg("msg.note.memoryleak3", req.getLocale()));

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
        bodyHtml.append(getErrMsg("msg.unknown.exception.occur", new String[] { e.getMessage() }, locale));
    } finally {
        responseToClient(req, res, getMsg("title.memoryleak3.page", locale), bodyHtml.toString());
    }
}
 
Example 3
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 4
Source File: BlogLanguageLocaleResolver.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Override
public Locale resolveLocale(HttpServletRequest request) {
	BlogLanguage blogLanguage = (BlogLanguage) request.getAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE);
	if (blogLanguage == null) {
		Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
		blogLanguage = blog.getLanguage(blog.getDefaultLanguage());
	}

	return (blogLanguage != null) ? Locale.forLanguageTag(blogLanguage.getLanguage()) : request.getLocale();
}
 
Example 5
Source File: RequestData.java    From sample.ferret with Apache License 2.0 5 votes vote down vote up
public RequestData(final HttpServletRequest request) {
    method = request.getMethod();
    uri = request.getRequestURI();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    characterEncoding = request.getCharacterEncoding();
    queryString = request.getQueryString();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    remoteUser = request.getRemoteUser();
    remoteAddress = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    localAddress = request.getLocalAddr();
    localHost = request.getLocalName();
    localPort = request.getLocalPort();
    authorizationScheme = request.getAuthType();
    preferredClientLocale = request.getLocale();
    allClientLocales = Collections.list(request.getLocales());
    contextPath = request.getContextPath();
    userPrincipal = request.getUserPrincipal();
    requestHeaders = getRequestHeaders(request);
    cookies = getCookies(request.getCookies());
    requestAttributes = getRequestAttributes(request);
}
 
Example 6
Source File: ValidatorContext.java    From validator-web with Apache License 2.0 5 votes vote down vote up
private Locale getLocale() {
    final WebContext context = WebContextThreadStack.get();
    if (context == null) {
        return Locale.getDefault();
    }
    final HttpServletRequest request = context.getHttpServletRequest();
    final ValidatorConfig validatorConfig = this.validatorFactory.getValidatorConfig();
    final String locale = request.getParameter(validatorConfig.getLanguageParameterName());
    if (StringUtils.hasText(locale)) {
        try {
            return LocaleUtils.toLocale(locale);
        } catch (IllegalArgumentException e) { }
    }
    return request.getLocale();
}
 
Example 7
Source File: AcceptLanguageHeaderResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Locale resolveLocale(final HttpServletRequest request) {

		if (Utils.isNotEmpty(request.getHeader("Accept-Language")))
			return request.getLocale();
		else
			return null;
	}
 
Example 8
Source File: UtilHttp.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static Locale getLocale(HttpServletRequest request, HttpSession session, Object appDefaultLocale) {
    // check session first, should override all if anything set there
    Object localeObject = session != null ? session.getAttribute("locale") : null;

    // next see if the userLogin has a value
    if (localeObject == null && session != null) { // SCIPIO: 2018-07-30: added null session check
        Map<?, ?> userLogin = (Map<?, ?>) session.getAttribute("userLogin");
        if (userLogin == null) {
            userLogin = (Map<?,?>) session.getAttribute("autoUserLogin");
        }

        if (userLogin != null) {
            localeObject = userLogin.get("lastLocale");
        }
    }

    // no user locale? before global default try appDefaultLocale if specified
    if (localeObject == null && UtilValidate.isNotEmpty(appDefaultLocale)) {
        localeObject = appDefaultLocale;
    }

    // finally request (w/ a fall back to default)
    if (localeObject == null) {
        localeObject = request != null ? request.getLocale() : null;
    }

    return UtilMisc.ensureLocale(localeObject);
}
 
Example 9
Source File: LossOfTrailingDigitsServlet.java    From easybuggy with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    boolean isValid = true;
    Locale locale = req.getLocale();
    String strNumber = req.getParameter("number");
    double number = NumberUtils.toDouble(strNumber, Double.NaN);
    try {
        if (Double.isNaN(number) || number <= -1 || 1 <= number) {
            isValid = false;
        }

        StringBuilder bodyHtml = new StringBuilder();
        bodyHtml.append("<form action=\"lotd\" method=\"post\">");
        bodyHtml.append(getMsg("msg.enter.decimal.value", locale));
        bodyHtml.append("<br><br>");
        if (!Double.isNaN(number) && isValid) {
            bodyHtml.append("<input type=\"text\" name=\"number\" size=\"18\" maxlength=\"18\" value=" + strNumber + ">");
        } else {
            bodyHtml.append("<input type=\"text\" name=\"number\" size=\"18\" maxlength=\"18\">");
        }
        bodyHtml.append(" + 1 = ");
        if (!Double.isNaN(number) && isValid) {
            bodyHtml.append(String.valueOf(number + 1));
        }
        bodyHtml.append("<br><br>");
        bodyHtml.append("<input type=\"submit\" value=\"" + getMsg("label.calculate", locale) + "\">");
        bodyHtml.append("<br><br>");
        bodyHtml.append(getInfoMsg("msg.note.lossoftrailingdigits", locale));
        bodyHtml.append("</form>");
        responseToClient(req, res, getMsg("title.lossoftrailingdigits.page", locale), bodyHtml.toString());

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
    }
}
 
Example 10
Source File: MojibakeServlet.java    From easybuggy with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    req.setCharacterEncoding("Shift_JIS");
    res.setContentType("text/html; charset=UTF-8");
    try {
        String string = req.getParameter("string");
        Locale locale = req.getLocale();

        StringBuilder bodyHtml = new StringBuilder();

        bodyHtml.append("<form action=\"mojibake\" method=\"post\">");
        bodyHtml.append(getMsg("description.capitalize.string", locale));
        bodyHtml.append("<br><br>");
        bodyHtml.append(getMsg("label.string", locale) + ": ");
        bodyHtml.append("<input type=\"text\" name=\"string\" size=\"100\" maxlength=\"100\">");
        bodyHtml.append("<br><br>");
        bodyHtml.append("<input type=\"submit\" value=\"" + getMsg("label.submit", locale) + "\">");
        bodyHtml.append("<br><br>");

        if (string != null && !"".equals(string)) {
            // Capitalize the given string
            String capitalizeName = WordUtils.capitalize(string);
            bodyHtml.append(getMsg("label.capitalized.string", locale) + " : " + encodeForHTML(capitalizeName));
        } else {
            bodyHtml.append(getMsg("msg.enter.string", locale));
        }
        bodyHtml.append("<br><br>");
        bodyHtml.append(getInfoMsg("msg.note.mojibake", locale));
        bodyHtml.append("</form>");

        responseToClient(req, res, getMsg("title.mojibake.page", locale), bodyHtml.toString());

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
    }
}
 
Example 11
Source File: SiteMessageHandler.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the html code which represents the page content
 *
 * @param data
 *            The structure which contains the informations about the page
 * @param nMode
 *            The mode in which displaying the page : normal or administration
 * @param request
 *            The request
 * @return The html code of a page
 */
private static String buildPageContent( PageData data, int nMode, HttpServletRequest request )
{
    Locale locale = null;
    HashMap<String, Object> model = new HashMap<>( );

    if ( request != null )
    {
        locale = request.getLocale( );
    }

    List<PageInclude> listIncludes = PageIncludeService.getIncludes( );

    for ( PageInclude pic : listIncludes )
    {
        pic.fillTemplate( model, data, nMode, request );
    }

    model.put( Markers.PAGE_NAME, ( data.getName( ) == null ) ? "" : data.getName( ) );
    model.put( Markers.PAGE_TITLE, ( data.getName( ) == null ) ? "" : data.getName( ) );
    model.put( Markers.PAGE_CONTENT, ( data.getContent( ) == null ) ? "" : data.getContent( ) );

    String strBaseUrl = ( request != null ) ? AppPathService.getBaseUrl( request ) : ""; // request could be null (method called by daemons or batch)

    // for link service
    model.put( Markers.BASE_URL, strBaseUrl );

    HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_PAGE_SITE_MESSAGE, locale, model );

    template.substitute( BOOKMARK_BASE_URL, ( request != null ) ? AppPathService.getBaseUrl( request ) : "" ); // request could be null (method called by
                                                                                                               // daemons or batch)

    return template.getHtml( );
}
 
Example 12
Source File: GoodsController.java    From SecKillShop with MIT License 4 votes vote down vote up
@RequestMapping("/details/{goodsId}")
@ResponseBody
public String goodsDetails(Model model, MiaoshaUser user, @PathVariable("goodsId") long id, HttpServletResponse response, HttpServletRequest request) {
    model.addAttribute("user", user);

    String html = redisService.get(GoodsKey.getGoodDetails, "" + id, String.class);
    if (!StringUtils.isEmpty(html)) {
        return html;
    }
    GoodsVo goodsVo = goodsService.getGoodsVoById(id);
    model.addAttribute("goodVo", goodsVo);

    //判断秒杀状态
    Long startDate = goodsVo.getStartDate().getTime();
    Long endData = goodsVo.getEndDate().getTime();
    Long now = System.currentTimeMillis();

    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if (now < startDate) {
        miaoshaStatus = 0;
        remainSeconds = (int) ((startDate - now) / 1000);
    } else if (now > endData) {
        miaoshaStatus = 2;
        remainSeconds = -1;
    } else {
        miaoshaStatus = 1;
        remainSeconds = 0;
    }

    model.addAttribute("miaoshaStatus", miaoshaStatus);
    model.addAttribute("remainSeconds", remainSeconds);

    //加入到缓存中
    WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
    html = thymeleafViewResolver.getTemplateEngine().process("goods_details", ctx);

    if (!StringUtils.isEmpty(html)) {
        redisService.set(GoodsKey.getGoodDetails, "" + id, html);
    }
    return html;
}
 
Example 13
Source File: AbstractLocaleContextResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Locale resolveLocale(HttpServletRequest request) {
	Locale locale = resolveLocaleContext(request).getLocale();
	return (locale != null ? locale : request.getLocale());
}
 
Example 14
Source File: SiteMapApp.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Build or get in the cache the page which contains the site map depending on the mode
 *
 * @param request
 *            The Http request
 * @param nMode
 *            The selected mode
 * @param plugin
 *            The plugin
 * @return The content of the site map
 */
@Override
public XPage getPage( HttpServletRequest request, int nMode, Plugin plugin )
{
    XPage page = new XPage( );
    String strKey = getKey( nMode, request );

    Locale locale = request.getLocale( );

    SiteMapCacheService siteMapCacheService = SiteMapCacheService.getInstance( );

    // Check the key in the cache
    String strCachedPage = siteMapCacheService.isCacheEnable( ) ? (String) siteMapCacheService.getFromCache( strKey ) : null;

    if ( strCachedPage == null )
    {
        // Build the HTML document
        String strPage = buildPageContent( nMode, request );

        // Add it to the cache
        if ( siteMapCacheService.isCacheEnable( ) )
        {
            synchronized( strKey )
            {
                siteMapCacheService.putInCache( strKey, strPage );
            }
        }

        page.setPathLabel( I18nService.getLocalizedString( PROPERTY_PATH_LABEL, locale ) );
        page.setTitle( I18nService.getLocalizedString( PROPERTY_PAGE_TITLE, locale ) );
        page.setContent( strPage );

        return page;
    }

    // The document exist in the cache
    page.setPathLabel( I18nService.getLocalizedString( PROPERTY_PATH_LABEL, locale ) );
    page.setTitle( I18nService.getLocalizedString( PROPERTY_PAGE_TITLE, locale ) );
    page.setContent( strCachedPage );

    return page;
}
 
Example 15
Source File: MonitoringFilter.java    From javamelody with Apache License 2.0 4 votes vote down vote up
private void putUserInfoInSession(HttpServletRequest httpRequest) {
	final HttpSession session = httpRequest.getSession(false);
	if (session == null) {
		// la session n'est pas encore créée (et ne le sera peut-être jamais)
		return;
	}
	// on ne met dans la session ces attributs que si ils n'y sont pas déjà
	// (pour que la session ne soit pas resynchronisée si serveur en cluster par exemple),
	// donc l'adresse ip est celle de la première requête créant une session,
	// et si l'adresse ip change ensuite c'est très étrange
	// mais elle n'est pas mise à jour dans la session
	if (session.getAttribute(SessionListener.SESSION_COUNTRY_KEY) == null) {
		// langue préférée du navigateur, getLocale ne peut être null
		final Locale locale = httpRequest.getLocale();
		if (!locale.getCountry().isEmpty()) {
			session.setAttribute(SessionListener.SESSION_COUNTRY_KEY, locale.getCountry());
		} else {
			session.setAttribute(SessionListener.SESSION_COUNTRY_KEY, locale.getLanguage());
		}
	}
	if (session.getAttribute(SessionListener.SESSION_REMOTE_ADDR) == null) {
		// adresse ip
		final String forwardedFor = httpRequest.getHeader("X-Forwarded-For");
		final String remoteAddr;
		if (forwardedFor == null) {
			remoteAddr = httpRequest.getRemoteAddr();
		} else {
			remoteAddr = httpRequest.getRemoteAddr() + " forwarded for " + forwardedFor;
		}
		session.setAttribute(SessionListener.SESSION_REMOTE_ADDR, remoteAddr);
	}
	if (session.getAttribute(SessionListener.SESSION_REMOTE_USER) == null) {
		// login utilisateur, peut être null
		final String remoteUser = httpRequest.getRemoteUser();
		if (remoteUser != null) {
			session.setAttribute(SessionListener.SESSION_REMOTE_USER, remoteUser);
		}
	}
	if (session.getAttribute(SessionListener.SESSION_USER_AGENT) == null) {
		final String userAgent = httpRequest.getHeader("User-Agent");
		session.setAttribute(SessionListener.SESSION_USER_AGENT, userAgent);
	}
}
 
Example 16
Source File: StringPlusOperationServlet.java    From easybuggy with Apache License 2.0 4 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    try {
        String strLength = req.getParameter("length");
        int length = NumberUtils.toInt(strLength, 0);
        String[] characters = req.getParameterValues("characters");
        Locale locale = req.getLocale();

        StringBuilder bodyHtml = new StringBuilder();
        bodyHtml.append("<form action=\"strplusopr\" method=\"post\">");
        bodyHtml.append(getMsg("description.random.string.generator", locale));
        bodyHtml.append("<br><br>");
        bodyHtml.append(getMsg("label.character.count", locale) + ": ");
        bodyHtml.append("<br>");
        if (length > 0) {
            bodyHtml.append("<input type=\"text\" name=\"length\" size=\"6\" maxlength=\"6\" value=\"" + length
                    + "\">");
        } else {
            bodyHtml.append("<input type=\"text\" name=\"length\" size=\"6\" maxlength=\"6\">");
        }
        bodyHtml.append("<br><br>");
        bodyHtml.append("<p>" + getMsg("label.available.characters", locale) + "</p>");

        appendCheckBox(characters, locale, bodyHtml, ALL_NUMBERS, "label.numbers");
        appendCheckBox(characters, locale, bodyHtml, ALL_UPPER_CHARACTERS, "label.uppercase.characters");
        appendCheckBox(characters, locale, bodyHtml, ALL_LOWER_CHARACTERS, "label.lowercase.characters");
        appendCheckBox(characters, locale, bodyHtml, ALL_SIGNS, "label.signs");

        bodyHtml.append("<input type=\"submit\" value=\"" + getMsg("label.submit", locale) + "\">");
        bodyHtml.append("<br><br>");

        if (length > 0) {
            // StringBuilder builder = new StringBuilder();
            String s = "";
            if (characters != null) {
                java.util.Random rand = new java.util.Random();
                log.info("Start Date: {}", new Date());
                for (int i = 0; i < length && i < MAX_LENGTH; i++) {
                    s = s + characters[rand.nextInt(characters.length)];
                    // builder.append(characters[rand.nextInt(characters.length)]);
                }
                log.info("End Date: {}", new Date());
            }
            bodyHtml.append(getMsg("label.execution.result", locale));
            bodyHtml.append("<br><br>");
            // bodyHtml.append(encodeForHTML(builder.toString()));
            bodyHtml.append(encodeForHTML(s));
        } else {
            bodyHtml.append(getMsg("msg.enter.positive.number", locale));
        }
        bodyHtml.append("<br><br>");
        bodyHtml.append(getInfoMsg("msg.note.strplusopr", locale));
        bodyHtml.append("</form>");
        responseToClient(req, res, getMsg("title.strplusopr.page", locale), bodyHtml.toString());

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
    }
}
 
Example 17
Source File: GoodsController.java    From goods-seckill with Apache License 2.0 4 votes vote down vote up
/**
	 * 商品列表展示
	 * 
	 * QPS: 500
	 * 
	 * 模拟:5000个并发 * 10次循环 = 50000个请求
	 * 
	 * 耗时:1分40秒
	 * 
	 * 分析:在并发访问过程中,数据库服务器CPU占用率达到了95%,负载最高到了3(mysql装在单核cpu的虚拟机上,内存1GB),
	 * 可见,并发访问中,造成QPS低的瓶颈在数据库。
	 * 
	 * 关于负载介绍: https://zhidao.baidu.com/question/186962244.html
	 * 
	 * @param model
	 * @param response
	 * @param miaoshaUserEntity
	 * @return
	 */
	@RequestMapping(value = "to_list", produces = "text/html")	// produces,指定返回thml页面
	@ResponseBody
	public String toList(
			Model model, HttpServletResponse response, HttpServletRequest request
//			@CookieValue(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN, required = false) String cookieToken,
//			@RequestParam(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN, required = false) String paramToken
//			MiaoshaUserEntity miaoshaUserEntity
			) {

//		String token = null;
//
//		if (StringUtils.isEmpty(paramToken)) {
//			if (!StringUtils.isEmpty(cookieToken)) {
//				token = cookieToken;
//			}
//		} else {
//			token = paramToken;
//		}
////		
//		if (StringUtils.isEmpty(token)) {
//			return "/login";
//		}
//
//		MiaoshaUserEntity miaoshaUserEntity = miaoshaUserService.getByToken(token, response);
//
//		if (miaoshaUserEntity == null) {
//			return "/login";
//		}
//
//		model.addAttribute("user", miaoshaUserEntity);
		
		// 添加html页面缓存到redis,也就是redis中缓存已经被渲染好的html静态页面
		// -------------------------------------------------
		
		// 取缓存redis缓存中的thymeleaf渲染好的html页面
		String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
		if (!StringUtils.isEmpty(html)) {
			return html;
		}
		
		List<GoodsVo> list = goodsService.selectGoodsVoList();
		model.addAttribute("goodsList", list);
		
		// 手动渲染thymeleaf模板
		SpringWebContext swc = new SpringWebContext(request, response, request.getServletContext(), 
				request.getLocale(), model.asMap(), applicationContext);	// 将model中数据放到SpringWebContext
		SpringTemplateEngine templateEngine = thymeleafViewResolver.getTemplateEngine();	
		html = templateEngine.process("goods_list", swc);	// thymeleaf模板引擎手动渲染出html页面
//		if (!StringUtils.isEmpty(html)) {
//			redisService.set(GoodsKey.getGoodsList, "", html);	// 将渲染好的html页面放进缓存
//		}
		return html;
		
		// -------------------------------------------------
	}
 
Example 18
Source File: CookieLocaleResolver.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Determine the default locale for the given request,
 * Called if no locale cookie has been found.
 * <p>The default implementation returns the specified default locale,
 * if any, else falls back to the request's accept-header locale.
 * @param request the request to resolve the locale for
 * @return the default locale (never {@code null})
 * @see #setDefaultLocale
 * @see javax.servlet.http.HttpServletRequest#getLocale()
 */
protected Locale determineDefaultLocale(HttpServletRequest request) {
	Locale defaultLocale = getDefaultLocale();
	if (defaultLocale == null) {
		defaultLocale = request.getLocale();
	}
	return defaultLocale;
}
 
Example 19
Source File: RequestContextUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Retrieve the current locale from the given request, using the
 * LocaleResolver bound to the request by the DispatcherServlet
 * (if available), falling back to the request's accept-header Locale.
 * <p>This method serves as a straightforward alternative to the standard
 * Servlet {@link javax.servlet.http.HttpServletRequest#getLocale()} method,
 * falling back to the latter if no more specific locale has been found.
 * <p>Consider using {@link org.springframework.context.i18n.LocaleContextHolder#getLocale()}
 * which will normally be populated with the same Locale.
 * @param request current HTTP request
 * @return the current locale for the given request, either from the
 * LocaleResolver or from the plain request itself
 * @see #getLocaleResolver
 * @see org.springframework.context.i18n.LocaleContextHolder#getLocale()
 */
public static Locale getLocale(HttpServletRequest request) {
	LocaleResolver localeResolver = getLocaleResolver(request);
	return (localeResolver != null ? localeResolver.resolveLocale(request) : request.getLocale());
}
 
Example 20
Source File: RequestContextUtils.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Retrieve the current locale from the given request, using the
 * LocaleResolver bound to the request by the DispatcherServlet
 * (if available), falling back to the request's accept-header Locale.
 * <p>This method serves as a straightforward alternative to the standard
 * Servlet {@link javax.servlet.http.HttpServletRequest#getLocale()} method,
 * falling back to the latter if no more specific locale has been found.
 * <p>Consider using {@link org.springframework.context.i18n.LocaleContextHolder#getLocale()}
 * which will normally be populated with the same Locale.
 * @param request current HTTP request
 * @return the current locale for the given request, either from the
 * LocaleResolver or from the plain request itself
 * @see #getLocaleResolver
 * @see org.springframework.context.i18n.LocaleContextHolder#getLocale()
 */
public static Locale getLocale(HttpServletRequest request) {
	LocaleResolver localeResolver = getLocaleResolver(request);
	return (localeResolver != null ? localeResolver.resolveLocale(request) : request.getLocale());
}