Tomcat 7.0.35 set HTTP response header Content-Type charset for static HTML files

非 Y 不嫁゛ 提交于 2019-12-18 02:49:25

问题


I am serving some static HTML files and a servlet all in a single war file from a standalone Tomcat 7.0.35 server using the HTTP Connector.

I want to specify the charset of all the static HTML files by setting the HTTP response header Content-Type=text/html;charset=UTF-8.

Tomcat by default serves HTML files with Content-Type=text/html (no charset portion).

I followed the instructions at:

http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8

But the header still contains Content-Type=text/html without the ;charset=UTF-8

My web.xml is reproduced below. Note that I tried changing the url-pattern to /*, *, /index.html, and index.html, but none of these worked.

FYI, the /index.html file is being correctly served by Tomcat (except for the missing ;charset=UTF-8). The /getData servlet is also working correctly, and I have successfully set the servlet's responses Content-Type=text/html;charset=UTF-8 by using response.setContentType("application/json;charset=UTF-8");.

Thanks for any help.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <filter>
        <filter-name>CharacterEncoding</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <url-pattern>/index.html</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>DataServlet</servlet-name>
        <servlet-class>com.rcg.data.web.DataServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DataServlet</servlet-name>
        <url-pattern>/getData</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

回答1:


Have you tried setting the MIME mapping to include the charset?

<mime-mapping>
    <extension>html</extension>
    <mime-type>text/html;charset=UTF-8</mime-type>
</mime-mapping>


来源:https://stackoverflow.com/questions/14716878/tomcat-7-0-35-set-http-response-header-content-type-charset-for-static-html-file

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