views:

142

answers:

2

When I read an UTF-8 encoded template with FreeMarker, special chars are rendered correctly in the browser, although freeMarkerConfig.getDefaultEncoding() returns "Cp1252". If I set freeMarkerConfig.setDefaultEncoding("UTF-8"), I see only question marks in the browser, although "UTF-8" is the actual encoding of the template file. In every case the http header "Content-Type: text/html; charset=UTF-8" is sent.

Any idea what is wrong?

A: 

The output encoding is those of your java machinery. If you create an output file with UTF-FOO, and pass this output file to freemarker generation, the output encoding will be UTF-FOO.

See Charset issues.

With ex. code :

  Template templévénmts;
  BufferedWriter writ;
  OutputStreamWriter encodé;

  encodé = new OutputStreamWriter(
   new FileOutputStream(new File(f_dirDestination, résultat)), "UTF-8");
  writ = new BufferedWriter(
   encodé);
  templévénmts = f_freemarker.getTemplate(modèle);
  templévénmts.process(f_rootDatas, writ);
  writ.close();

You can also use FileWriterWithEncoding in commons io.

Istao
`setDefaultEncoding` is about the encoding of the input. http://freemarker.org/docs/api/freemarker/template/Configuration.html#setDefaultEncoding%28java.lang.String%29The input is UTF-8 encoded and I tell FreeMarker that it would be UTF-8 encoded, but it works only when Cp1252 encoding is used for reading the input.
deamon
What is your freemarker version and in what context do you use it ?
Istao
I'm using FreeMarker 2.3.16 together with JAX-RS (implementation: Jersey) and, in the end, Servlets.
deamon
If you set all input ways to UTF-8, and process your template to a file on your local system with UTF-8 settings, is the result file OK ?
Istao
A: 

Well, it definitely looks like regardless of the fact that you think your input is UTF-8 encoded, in reality it is indeed Cp1252 encoded. Can you doublecheck, i.e. with a hex-editor. I second Istao's opinion -- try processing your template file to a local file and check the results.

Attila Szegedi
I've checked the encoding with jEdit, what handles encodings very fine. The curios thing is, that it even works with the same template files on a system with UTF-8 as default encoding. So FreeMarker should use UTF-8 for reading the input files.
deamon