ここで説明されているように、Spring MVC で Freemarker テンプレートローダーをラップして、html ページでデフォルトのエスケープを行います。
したがって、java.io.Reader からのコンテンツを自分の文字列でラップする必要があります。それを読み取ったり、文字列に変換したり、自分自身を実装したりしないでください。一般的な共通ライブラリにWrappingReaderまたは com.google.common.io.MultiReader (公開されていない) に似たクラスはありますか?
私の実装:
import com.google.common.io.CharStreams;
import com.google.common.io.InputSupplier;
...
private final TemplateLoader delegate;
@Autowired
public HtmlEscapingTemplateLoader(ResourceLoader resourceLoader)
{
delegate = new SpringTemplateLoader(resourceLoader, "/WEB-INF/templates/");
}
@Override
public Reader getReader(Object templateSource, String encoding) throws IOException
{
// collecting readers
Reader prologue = new StringReader("<#escape x as x?html>");
Reader originalReader = delegate.getReader(templateSource, encoding);
Reader epilogue = new StringReader("</#escape>");
// concatenating readers
return merge(prologue, originalReader, epilogue);
}
protected Reader merge(Reader prologue, Reader originalReader, Reader epilogue) throws IOException
{
return CharStreams.join(
Arrays.asList(new ReaderSupplier(prologue), new ReaderSupplier(originalReader), new ReaderSupplier(
epilogue))).getInput();
}
private static class ReaderSupplier
implements InputSupplier<Reader>
{
private final Reader reader;
public ReaderSupplier(Reader reader)
{
this.reader = reader;
}
@Override
public Reader getInput() throws IOException
{
return reader;
}
}
私が使用する CharStreams は、@com.google.common.annotations.Beta としてマークされています。では、CharStreams を使用せずに、より確実な方法で書き直すことはできますか?