What is the best way to ensure HTML entities are escaped in StringTemplate

試著忘記壹切 提交于 2019-12-03 22:25:18

问题


Assuming the following string template, is being given a list of Java Bean objects:

<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:

class Person {
    ....
    public getName() { ... }
    public getEmail() { ... }
}

The getName() and getEmail() methods don't return sanitised (escaped html entities). How do you get around this?


回答1:


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>&lt;b&gt;Dave&lt;/b&gt; dave@ohai.com</li><li>&lt;b&gt;Nick&lt;/b&gt; nick@kthxbai.com</li></ul>



回答2:


It's not necessary to write your own renderer for this. You may use the builtin renderer 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>


来源:https://stackoverflow.com/questions/14331081/what-is-the-best-way-to-ensure-html-entities-are-escaped-in-stringtemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!