Вопрос

I'm looking for functional way to set default character encoding for HTTP responses for Geronimo 3 with Tomcat. It seems there is a lot of work-arounds, but not any way to easily set some property in some file like in case of Apache Httpd. (Apache Httpd has AddDefaultCharset used for all responses.) I've tried add attributes useBodyEncodingForURI and URIEncoding to <connector> elements in var/catalina/server.xml.

<Connector name="TomcatWebConnector"
    port="${HTTPPort + PortOffset}"
    address="${ServerHostname}"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="${HTTPSPort + PortOffset}"
    useBodyEncodingForURI="true"
    URIEncoding="UTF-8"
    executor="DefaultThreadPool"/>

But it does not work. I still get header Content-Type text/html;charset=ISO-8859-1 in response. Another solution is to programaticaly change headers in application (e.g. via filter or valve), but I don't find it systemic.

Это было полезно?

Решение

I returned to my question I had asked two months ago. I know now that the solution using a filter is not any workaround, but common way. Just write a filter class:

package eu.barbucha.tests;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingSettingFilter implements Filter {
    private final String enc = "utf-8";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain fc)
            throws IOException, ServletException {
        request.setCharacterEncoding(enc);
        resp.setCharacterEncoding(enc);
        fc.doFilter(request, resp);
    }

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

And assign the filter with all URIs in the WEB-INF/web.xml file:

<filter>
    <description>Filter setting encoding</description>
    <filter-name>enc-filter</filter-name>
    <filter-class>eu.barbucha.tests.EncodingSettingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>enc-filter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

That's all.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top