How do I set the timezone in Tomcat for a single web app?

前端 未结 8 1896
春和景丽
春和景丽 2021-02-05 13:00

What is the best way to set the time zone in Tomcat for a single web app? I\'ve seen options for changing the command-line parameters or environment variables for Tomcat, but is

8条回答
  •  别那么骄傲
    2021-02-05 13:53

    With Java 7/Tomcat 7, there's a workaround/hack that allows the developer to set a unique timezone per webapp. We had to implement this in our application, as we had to support multiple webapps that run with different default timezones in the same JVM.

    Other solutions that I've seen on stack overflow do not completely address the issue.

    • Using Timezone.setDefault() doesn't work, because it changes the timezone across the JVM.
    • Using servlet filters is completely thread unsafe, and does not account for child threads
    • Using SecurityManager approaches also does not account for child thread related timezone issues.

    I also investigated the Java source code for TimeZone, I found a way to have a dynamic timezone returned as the default timezone for all callers by injecting a custom implementation of the JavaAWTAccess interface. This can be done by looking at the Thread class loader, and determining the actual webapp context from it, then handling that appropriately based on some webapp name to timezone mapping.

    Once again, this is application server specific, and must be done differently for Tomcat, Jetty, Jboss, etc. This approach is also JVM implementation specific (only works on Oracle/Sun), but I believe can be extended to OpenJDK and others.

    We have a verified working solution for Oracle JDK 7 SE + Tomcat 7, deployed on both Windows and Linux, hosting multiple webapps in different timezones.

提交回复
热议问题