Tomcat 7 org.apache.catalina.filters.AddDefaultCharsetFilter not using UTF-8

一个人想着一个人 提交于 2019-12-23 05:43:09

问题


I have a Tomcat 7 webapp and am having problems with character sets. My goal is to force everything into UTF-8 and just be done with it. I'm actually surprised that in 2014 not everything defaults to UTF-8...

I read the docs and have uncommented the org.apache.catalina.filters.AddDefaultCharsetFilter filter in the system's default web.xml.

/etc/tomcat/web.xml:

<filter>
    <filter-name>setCharacterEncodingFilter</filter-name>
    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <async-supported>true</async-supported>
</filter>

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

I have also added URIEncoding="UTF-8" to the Connectors in the server.xml:

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

Doing this (and a bunch of other stuff like jdbc params) seems to get the request into UTF-8. But how do I force the Response to UTF-8?

i.e.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.printf("Req: %s\n", req.getCharacterEncoding());
    System.out.printf("Resp: %s\n", resp.getCharacterEncoding());

yields:

Req: UTF-8
Resp: ISO-8859-1

Thanks


回答1:


I didn't read your question carefully enough before. The default response encoding is ISO-8859-1 due to the HTTP standard. If you want to change it, you'll have to set the encoding on the response yourself.

What you really ought to do is read the Tomcat FAQ which has an entry for the exact question you have asked: What can you recommend to just make everything work? (How to use UTF-8 everywhere).




回答2:


It looks like you are talking about two different filters:

  • AddDefaultCharsetFilter (applies to response)
  • SetCharacterEncodingFilter (applies to request)

In your case, you want to use AddDefaultCharsetFilter as explained here:

http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Add_Default_Character_Set_Filter



来源:https://stackoverflow.com/questions/22768859/tomcat-7-org-apache-catalina-filters-adddefaultcharsetfilter-not-using-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!