1 52 53 package freemarker.template.utility; 54 55 import java.io.IOException ; 56 import java.io.Writer ; 57 import java.util.Map ; 58 59 import freemarker.template.TemplateTransformModel; 60 61 89 public class HtmlEscape implements TemplateTransformModel { 90 91 private static final char[] LT = "<".toCharArray(); 92 private static final char[] GT = ">".toCharArray(); 93 private static final char[] AMP = "&".toCharArray(); 94 private static final char[] QUOT = """.toCharArray(); 95 96 public Writer getWriter(final Writer out, Map args) 97 { 98 return new Writer () 99 { 100 public void write(char c) 101 throws 102 IOException 103 { 104 switch(c) 105 { 106 case '<': out.write(LT, 0, 4); break; 107 case '>': out.write(GT, 0, 4); break; 108 case '&': out.write(AMP, 0, 5); break; 109 case '"': out.write(QUOT, 0, 6); break; 110 default: out.write(c); 111 } 112 } 113 114 public void write(char cbuf[], int off, int len) 115 throws 116 IOException 117 { 118 int lastoff = off; 119 int lastpos = off + len; 120 for (int i = off; i < lastpos; i++) 121 { 122 switch (cbuf[i]) 123 { 124 case '<': out.write(cbuf, lastoff, i - lastoff); out.write(LT, 0, 4); lastoff = i + 1; break; 125 case '>': out.write(cbuf, lastoff, i - lastoff); out.write(GT, 0, 4); lastoff = i + 1; break; 126 case '&': out.write(cbuf, lastoff, i - lastoff); out.write(AMP, 0, 5); lastoff = i + 1; break; 127 case '"': out.write(cbuf, lastoff, i - lastoff); out.write(QUOT, 0, 6); lastoff = i + 1; break; 128 } 129 } 130 int remaining = lastpos - lastoff; 131 if(remaining > 0) 132 { 133 out.write(cbuf, lastoff, remaining); 134 } 135 } 136 public void flush() throws IOException { 137 out.flush(); 138 } 139 140 public void close() { 141 } 142 }; 143 } 144 } 145 | Popular Tags |