[英]What is the best way to ensure HTML entities are escaped in StringTemplate
Assuming the following string template, is being given a list of Java Bean objects: 假设下面的字符串模板,将被提供Java Bean对象的列表:
<ul>$people:{p|<li>$p.name$ $p.email</li>}$</ul>
ie the list of people might contain Person
objects which you may or may not have the ability to enhance/extend: 即人员列表可能包含您可能无法增强/扩展的
Person
对象:
class Person {
....
public getName() { ... }
public getEmail() { ... }
}
The getName()
and getEmail()
methods don't return sanitised (escaped html entities). getName()
和getEmail()
方法不会返回经过清理的(转义的html实体)。 How do you get around this? 您如何解决这个问题?
You may use a custom renderer, for example: 您可以使用自定义渲染器,例如:
public static class HtmlEscapeStringRenderer implements AttributeRenderer {
public String toString(Object o, String s, Locale locale) {
return (String) (s == null ? o : StringEscapeUtils.escapeHtml((String) o));
}
}
Then in the template indicate you want it escaped: 然后在模板中指示您希望其转义:
$p.name;format="html"$
That said, you may prefer to scrub the data on input, convert before sending to the template, send a decorated person to the template, etc. 也就是说,您可能更喜欢清理输入的数据,在发送到模板之前进行转换,将经过装饰的人发送到模板等。
public class App {
public static void main(String[] args) {
STGroupDir group = new STGroupDir("src/main/resource", '$', '$');
group.registerRenderer(String.class, new HtmlEscapeStringRenderer());
ST st = group.getInstanceOf("people");
st.add("people", Arrays.asList(
new Person("<b>Dave</b>", "dave@ohai.com"),
new Person("<b>Nick</b>", "nick@kthxbai.com")
));
System.out.println(st.render());
}
public static class HtmlEscapeStringRenderer implements AttributeRenderer {
public String toString(Object o, String s, Locale locale) {
return (String) (s == null ? o : StringEscapeUtils.escapeHtml((String) o));
}
}
}
This outputs: 输出:
<ul><li><b>Dave</b> dave@ohai.com</li><li><b>Nick</b> nick@kthxbai.com</li></ul>
It's not necessary to write your own renderer for this. 无需为此编写自己的渲染器。 You may use the builtin renderer org.stringtemplate.v4.StringRenderer
您可以使用内置渲染器org.stringtemplate.v4.StringRenderer
group.registerRenderer(String.class, new StringRenderer());
and add in your template : 并添加您的模板:
<ul>$people:{p|<li>$p.name;format="xml-encode"$ $p.email;format="xml-encode"$</li>}$</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.