0

I'm mounting a directory which has translations inside of JavaScript. In order for the browser to render them properly, I need to pass a character encoding header.

The directory is mounted through Spring's resource handler like so:

public class WebMvcConfig extends WebMvcConfigurerAdapter implements ResourceLoaderAware {


    @Override
    public void addResourceHandlers(@Nonnull final ResourceHandlerRegistry registry) { registry.addResourceHandler("/app/static/scripts/**")
            .addResourceLocations("/static/scripts/")
            .setCachePeriod((int) TimeUnit.DAYS.toSeconds(365));
        ...
    }

...

}

I haven't found an obvious way to set the default character encoding to UTF-8. Any ideas? I'm on Spring MVC 3.2.4.

ggmathur
  • 833
  • 5
  • 12
  • Have you made sure the translation files are saved in UTF-8? Perhaps with [BOM](http://en.wikipedia.org/wiki/Byte_order_mark) to ensure correct encoding detection. Also potentially relevant: http://stackoverflow.com/a/5933805/1594449 and perhaps http://stackoverflow.com/questions/5141403/utf-8-encoding-in-spring-mvc-problem-with-forms – gknicker Jan 24 '15 at 02:10
  • The translations are embedded in the JS, for example: "Find":[null,"Ƒīṅđ"] – ggmathur Jan 24 '15 at 02:14

1 Answers1

2

Though Interceptors don't get called when requesting resources, filters do. All I had to do was add a filter that set the response's character encoding to UTF-8.

/**
 * Sets character encoding on the request and response.
 *
 * @author gaurav
 */
public class CharacterEncodingFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            response.setCharacterEncoding("UTF-8");
        } finally {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() { }
}
ggmathur
  • 833
  • 5
  • 12