简体   繁体   中英

Spring Boot: how to set encoding in JSPF files to UTF-8

I am struggling with encoding of jspf files. When I insert a german umlaut (eg "ä") in the jspf the output in the browser is broken (some unreadable character).

I start Spring Boot from within eclipse, the jspf file itself is encoded as UTF-8.

Note that this issue only applies to jspf files . With jsp files everything is working fine as they contain the page directive <%@ page contentType="text/html;charset=UTF-8"%> .

This is what I tried so far (none of them worked):

  • Insert spring.http.encoding.charset=UTF-8, spring.http.encoding.enabled=true, spring.http.encoding.force=true in application.properties
  • Insert server.servlet.encoding.charset=UTF-8, server.servlet.encoding.enabled=true, server.servlet.encoding.force=true in application.properties
  • Use -Dfile.encoding=UTF-8 as JVM arg
  • Use a CharacterEncodingFilter

The only working option is to insert page directive in the jspf file:

<%@ page contentType="text/html;charset=UTF-8"%>

But this has to be inserted in every jspf file. I'm looking for some global option.

By default the JSPF Encoding its ISO-8859-1, the solution you found is the correct to change the encoding, and as you say could be a pain modify every single file. The ways I know for change that in the easiest way is adding this to your web.xml

<jsp-config>
<jsp-property-group>
    <url-pattern>/*</url-pattern>
    <page-encoding>UTF-8</page-encoding>
</jsp-property-group>

Or change the context of your application server, idk if you are using Tomcat or another one.

The solution provided cannot be applied directly to Spring Boot as it doesn't "have" a web.xml.

Instead you have to configure the property group programmatically:

@Component
public class JspContextCustomizer implements TomcatContextCustomizer {
  @Override
  public void customize(Context context) {
    JspPropertyGroup group = new JspPropertyGroup();
    group.addUrlPattern("/*");
    group.setPageEncoding("UTF-8");
    context.setJspConfigDescriptor(new JspConfigDescriptorImpl(
      Collections.singletonList(new JspPropertyGroupDescriptorImpl(group)),
      Collections.emptyList()));
  } 
}

This works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM