servlet

wa7juj8i  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(312)

在我的项目中,我使用的是maven+GoogleGuice+Java8,我检查了我的网页响应是否没有编码,问题出在后端。
我找到的解决方案是更新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>

但它不起作用。有人能帮忙吗?在我的项目中全局配置它?

jc3wubiy

jc3wubiy1#

首先,感谢您@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() {}
 };
}

相关问题