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

前端 未结 8 1916
春和景丽
春和景丽 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:29

    The only way I found is to setup a filter and change the timezone in the filter,

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        TimeZone savedZone = TimeZone.getDefault();
        TimeZone.setDefault(webappZone);
        chain.doFilter(request, response);
        TimeZone.setDefault(savedZone);
    }
    

    The setDefault() changes the zone for the thread. So everything running in the thread inside the filter will have a different default timezone. We have to change it back because the thread is shared by other apps. You also need to do the same for your init(), destroy() methods and any other thread you might start in your application.

    I had to do this because a third-party library assumes default timezone and we don't have source code. It was a mess because this changes log timezone but we don't want log in different times. The correct way to handle this is to use a specific timezone in any time value exposed to end users.

提交回复
热议问题