确保在StringTemplate中转义HTML实体的最佳方法是什么 [英] What is the best way to ensure HTML entities are escaped in StringTemplate

查看:345
本文介绍了确保在StringTemplate中转义HTML实体的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下字符串模板,正在给出一个Java Bean对象列表:

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() { ... }
}

getName() getEmail()方法不返回已清理(转义的html实体)。你怎么解决这个问题?

The getName() and getEmail() methods don't return sanitised (escaped html entities). 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));
        }
    }
}

此输出:

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

这篇关于确保在StringTemplate中转义HTML实体的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆