Servlet使用maven+guide进行全局编码



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

我找到的解决方案是更新HttpServlet响应:

@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>

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

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

正如他所指出的:

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

要使用Guice解决此问题,我们需要在文档中的Servlet模块中创建一个筛选器。

我在configureServlet((中添加了过滤器:

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() {}
};
}

最新更新