0

在我的项目中,我使用的是 Maven + Google Guice + Java 8,我检查了我的网页响应没有编码,问题出在后端。

我发现修复它的解决方案是更新 HttpServletResponse:

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
...
resp.setContentType("text/html; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
}

但是我想全局配置它,而不仅仅是一个 Servlet,为此我尝试了他们在此处解释的内容,将编码添加到 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>YOUR_COMPANY</groupId>
    <artifactId>YOUR_APP</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.java.version>1.8</project.java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <!-- Your dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${project.java.version}</source>
                    <target>${project.java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

但它没有用。有人可以帮忙吗?在我的项目中全局配置它?

4

1 回答 1

0

首先,感谢@Robert 的回答和帮助。

正如他所指出的:

maven 配置只影响源代码中存在的字符串如何被读取和写入类文件。您不能以这种方式配置 servlet 响应编码。

要使用 Guice 解决它,我们需要在ServletModule中创建一个过滤器,我们可以在文档中找到。

我将过滤器添加到 configureServlets() 中:

filter("/*").through(createServletFilter());

过滤器创建是:

protected Filter createServletFilter() {
 return new Filter() {
   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
       throws IOException, ServletException {
     response.setContentType("text/html; charset=UTF-8");
     response.setCharacterEncoding("UTF-8");
     chain.doFilter(request, response);
   }

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

   @Override
   public void destroy() {}
 };
}
于 2021-07-05T13:18:05.997 回答