In my project, I'm using Maven + Google Guice + Java 8, and I checked that my webpage responses were not encoded and the problem is from the backend side.
The solution I found to fix it was to update the HttpServletResponse:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
...
resp.setContentType("text/html; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
}
But I would like to configure it globally and not only for one Servlet, to do it I tried what they explained here adding encoding to the 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>
But it didn't work. Could someone help with it? Configuring it globally in my project?
Firstly, thank you @Robert for your answer and help.
As he pointed out:
The maven configuration only affects how strings present in your source code are read and written into the class files. You can't configure a servlet response encoding this way.
To solve it using Guice, we need to create a filter in our ServletModule as we can find in the documentation.
I did it adding the filter to configureServlets():
filter("/*").through(createServletFilter());
And the filter create was:
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() {}
};
}