我正在安装一个在JavaScript中有翻译的目录。为了让浏览器正确呈现它们,我需要传递一个字符编码头。
目录是通过Spring的资源处理程序挂载的,如下所示:
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));
...
}
...
}
我还没有找到一种将默认字符编码设置为UTF-8的明显方法。有任何想法吗?我是关于Spring MVC 3.2.4。
答案 0 :(得分:2)
虽然拦截器在请求资源时不会被调用,但是过滤器可以。我所要做的就是添加一个过滤器,将响应的字符编码设置为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() { }
}