我将 Freemarker 模板加载器包装在 Spring MVC 中,如此处所述,以在 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 的情况下以更可靠的方式重写它?