Retrieving timezone information from a request in Spring 4.0

There is a new function for obtaining time zone information in the web request object. See Section 16.9.1 at http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html#mvc-timezone

But I can’t decide how we can get the time zone information from the request, or which method to use to get the time zone information?

After viewing and then using the source code https://github.com/spring-projects/spring-framework/blob/v4.0.7.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/support /RequestContext.java#L242 I tried to print it manually

println WebUtils.getSessionAttribute(request, SessionLocaleResolver.class.getName() + ".TIME_ZONE")

Any help?

+4
source share
2 answers

Simply add the type argument of the method TimeZoneto get it.

@RequestMapping
public String foo(TimeZone timezone) { ... }

That should do it.

If you really want to do this, use the method RequestContextUtils.getTimeZone(request).

@RequestMapping
public String foo(HttpServletRequest request) {
    TimeZone timezone = RequestContextUtils.getTimeZone(request);
    ...
}
+8
source

I figured it out a bit, and one problem is that there is no default set TimeZonethat looks like an oversight; RequestContextUtils.getTimeZone(request)should return the server time zone if nothing is available.

This is easy enough to fix; add dependency injection in BootStrap.groovyfor the "localeResolver" bean and some code to set the default time zone in the resolver:

class BootStrap {

   def localeResolver

   def init = {
      if (!localeResolver.defaultTimeZone) {
         localeResolver.defaultTimeZone = TimeZone.getDefault()
         // or hard-code to a known instance, e.g. TimeZone.getTimeZone('America/New_York')
      }
   }
}

TimeZone Spring; 2005 .

Grails LocaleResolver AcceptHeaderLocaleResolver ( TimeZone) SessionLocaleResolver. , , resolver ( null - Grails), , , request.getLocale(), Accept-Language. , - . , LocaleChangeInterceptor, "lang" Locale. .

-, . , , , , , LocaleResolver,

import org.springframework.web.servlet.i18n.SessionLocaleResolver

...

session[SessionLocaleResolver.TIME_ZONE_SESSION_ATTRIBUTE_NAME] =
    TimeZone.getTimeZone(user.timeZoneId)

JavaScript TimeZone Ajax. . .

+3

Source: https://habr.com/ru/post/1569296/


All Articles