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

后端 未结 2 1561
面向向阳花
面向向阳花 2021-01-07 06:07

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

    $people:{p|
  • $p.name$ $p.email
  • }$
2条回答
  •  盖世英雄少女心
    2021-01-07 06:54

    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("Dave", "dave@ohai.com"),
                    new Person("Nick", "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:

    • <b>Dave</b> dave@ohai.com
    • <b>Nick</b> nick@kthxbai.com

提交回复
热议问题