1 16 17 package org.springframework.web.util; 18 19 import org.springframework.util.StringUtils; 20 21 42 public abstract class HtmlUtils { 43 44 47 private static final HtmlCharacterEntityReferences characterEntityReferences = 48 new HtmlCharacterEntityReferences(); 49 50 private static final String PARAMETER_DELIMETER = "&"; 51 52 53 65 public static String htmlEscape(String input) { 66 if (input == null) { 67 return null; 68 } 69 StringBuffer escaped = new StringBuffer (input.length() * 2); 70 for (int i = 0; i < input.length(); i++) { 71 char character = input.charAt(i); 72 String reference = characterEntityReferences.convertToReference(character); 73 if (reference != null) { 74 escaped.append(reference); 75 } 76 else { 77 escaped.append(character); 78 } 79 } 80 return escaped.toString(); 81 } 82 83 95 public static String htmlEscapeDecimal(String input) { 96 if (input == null) { 97 return null; 98 } 99 StringBuffer escaped = new StringBuffer (input.length() * 2); 100 for (int i = 0; i < input.length(); i++) { 101 char character = input.charAt(i); 102 if (characterEntityReferences.isMappedToReference(character)) { 103 escaped.append(HtmlCharacterEntityReferences.DECIMAL_REFERENCE_START); 104 escaped.append((int) character); 105 escaped.append(HtmlCharacterEntityReferences.REFERENCE_END); 106 } 107 else { 108 escaped.append(character); 109 } 110 } 111 return escaped.toString(); 112 } 113 114 123 public static String htmlEscapeQueryStringParameters(String queryString) { 124 if (!StringUtils.hasText(queryString)) { 125 return ""; 126 } 127 StringBuffer buffer = new StringBuffer (queryString.length() * 2); 128 String [] parameters = StringUtils.tokenizeToStringArray(queryString, PARAMETER_DELIMETER); 129 if (parameters.length > 0) { 130 for (int i = 0; i < parameters.length; ++i) { 131 String parameter = parameters[i]; 132 buffer.append(HtmlUtils.htmlEscape(parameter)); 133 if (i < parameters.length - 1) { 134 buffer.append(PARAMETER_DELIMETER); 135 } 136 } 137 } 138 return buffer.toString(); 139 } 140 141 153 public static String htmlEscapeHex(String input) { 154 if (input == null) { 155 return null; 156 } 157 StringBuffer escaped = new StringBuffer (input.length() * 2); 158 for (int i = 0; i < input.length(); i++) { 159 char character = input.charAt(i); 160 if (characterEntityReferences.isMappedToReference(character)) { 161 escaped.append(HtmlCharacterEntityReferences.HEX_REFERENCE_START); 162 escaped.append(Integer.toString((int) character, 16)); 163 escaped.append(HtmlCharacterEntityReferences.REFERENCE_END); 164 } 165 else { 166 escaped.append(character); 167 } 168 } 169 return escaped.toString(); 170 } 171 172 191 public static String htmlUnescape(String input) { 192 if (input == null) { 193 return null; 194 } 195 return new HtmlCharacterEntityDecoder(characterEntityReferences, input).decode(); 196 } 197 198 } 199 | Popular Tags |