velocity 替换\n 换行符 为html

用velocity 将字符串中的”\n”换行符转变成<br/>现在非常常用下面提供两种解决方案

如果用如下方法经过测试不能够正常工作

#set($comments = $stringUtils.replace($comments, "\n", "<br />")) 

但是如果采用jdk1.4中的 String.replaceAll(new, old) 可以解决
解决方案1:

#set($comments = $comments.replaceAll("\n", "<br />) 

解决方法2:如上所提到的失败的方法,可以采用以下解决方案在velocity中添加如下方法

public void testCommonsStringUtils() throws Exception { 
    VelocityEngine engine = new VelocityEngine(); 
    engine.init(); 
    VelocityContext ctx = new VelocityContext(); 
    ctx.put("stringUtils", new StringUtils()); 
    ctx.put("comments", "this is a \n newline test"); 
    ctx.put("newline", "\n"); 
    ctx.put("break", "<br />"); 
    String template = "#set($comments = $stringUtils.replace($comments,$newline,$break))"; 
    template += "$comments"; 
    StringWriter writer = new StringWriter(); 
    engine.evaluate(ctx, writer, "", template); 
    assertEquals("this is a <br /> newline test", writer.toString()); 
} 

转载自:velocity 替换\n 换行符 为html <br />

你可能感兴趣的:(velocity 替换\n 换行符 为html
)