如何在Spring MVC中将字符编码设置为UTF8?

时间:2018-01-26 18:13:36

标签: java encoding utf-8

问题:我想将编码设置为UTF-8。不过,我有Content-Type text/html;charset=ISO-8859-1 我怎样才能做到这一点?我在这个问题中遵循了接受的答案:How to get UTF-8 working in Java webapps?

是:

  • FreeMarker的

  • Spring 5.0.2

  • Ubuntu Linux 17.04

  • Tomcat 8.5

  • Java 9

server.xml连接器对象中 URIEncoding="UTF-8"

内部HTML标题: <meta charset="UTF-8" /><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />

在实现WebMvcConfigurer的类中:

@Bean
public FreeMarkerViewResolver freemarkerViewResolver()
{
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();

    resolver.setCache(true);
    resolver.setSuffix(".ftl");
    resolver.setContentType("text/html;charset=UTF-8");

    return resolver;
}

同时

FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setDefaultEncoding("UTF-8");

使用过滤器:

public class CharsetFilter implements Filter
{

    private String encoding;

    public void init(FilterConfig config) throws ServletException
    {
        encoding = config.getInitParameter("requestEncoding");

        if (encoding == null)
        {
            encoding = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException
    {
        if (null == request.getCharacterEncoding())
        {
            request.setCharacterEncoding(encoding);
        }

        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        next.doFilter(request, response);
    }
}

在web.xml中:

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

0 个答案:

没有答案