velocity的html语义转换

    xiaoxiao2024-05-22  102

    1、html语义转换(1)velocity1.5版本默认不转换html(2)velocity1.6、1.7版本默认转换html(3)虽然转换后的html能够防止xss,但是,有时页面就是需要不转换的数据,如json字符串,可以通过#noescape()$!{data}#end即可,注意webx中一般配置了velocity,但是spring mvc中没有配置velocity,一定要注意看清楚2、velocity中加入java工具类velocity页面展示时经常需要日期格式化,字符串判断等需求,可以在将java工具类放在velocity中供页面使用,如(1)字符串工具类

    context.put("stringUtils", new StringUtils());

    页面使用

    #if($!stringUtils.contains($!{roleId},"1")) #end

    (2)日期工具类

    context.put("date", new DateTool());

    页面使用

    $!date.format('yyyy-MM-dd',$!visitor.visitorStart)

    3、有时候velocity的模板内容可能是存在数据库或者缓存中的字符串,这时候需要将模板内容读出后,将模板中的变量进行替换,生成模板内容,可以使用如下工具类

    import java.io.StringWriter; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import com.laiwang.common.collect.Maps; /** * @author liangtu on 2017年5月26日 */ public class VelocityUtil { /** * 字符串模板生成velocity模板内容 * * @param content * 字符串模板 * @param model * 字符串模板中的变量 */ public static String generateContent(String content, Map<String, Object> model) { if (StringUtils.isBlank(content)) { return ""; } Velocity.init(); VelocityContext context = new VelocityContext(); if (MapUtils.isNotEmpty(model)) { for (Entry<String, Object> entry : model.entrySet()) { context.put(entry.getKey(), entry.getValue()); } } StringWriter stringWriter = new StringWriter(); Velocity.evaluate(context, stringWriter, "velocity", content); return stringWriter.toString(); } }

    后续会陆续补充……

    最新回复(0)