问题
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?
回答1:
Set the content type property into the FreeMarkerViewResolver.
Spring 4.2 example
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setContentType("text/html; charset=utf-8");
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl.html");
resolver.setRequestContextAttribute("rc");
return resolver;
}
回答2:
In the case you are using spring framework and a MimeMessage to send the email try setting content via a MimeMessagePreparator as follows (I skip the mimemessagepreparator method getMessagePreparator as the important thing is how to set content):
// Create the message helper from the received mimemessage on the preparator
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// ... include the from, to, subject, freemarker html generation here... text is the String variable with generated html
// Set the content as follows instead of helper.setText(text, true);
helper.getMimeMessage().setContent(text, "text/html;charset=utf-8");
This worked for me and browsers are displaying chars correctly when sending emails.
The implied classes are:
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import javax.mail.internet.MimeMessage;
Also be sure that your workspace has a default encoding of UTF-8 for the template files by right clicking on them looking properties if you are using eclipse IDE.
Hope this helps.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/3434094/freemarker-encoding-confusion