Last active
August 29, 2015 14:23
-
-
Save takawitter/0ac3878bfdb3f482f4ad to your computer and use it in GitHub Desktop.
ちゃんと5回呼ばれるやつ(シングルクオートをバッククオートに修正)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class HtmlEncoderTest { | |
static public void main(String[] args) { | |
System.out.println(new HtmlEncoder().encode("<script>alert('注意!');</script>")); | |
System.out.println(HtmlEncoder.count); | |
} | |
} | |
abstract class Encoder { | |
private Map<Character, String> conversionTable = | |
new HashMap<Character, String>(); | |
protected void addConversion(char c, String s) { | |
conversionTable.put(c, s); | |
} | |
protected void addNoConversion(char c) { | |
conversionTable.put(c, String.valueOf(c)); | |
} | |
protected void addNoConversion (char[] collection) { | |
for (char c : collection) { | |
addNoConversion(c); | |
} | |
} | |
abstract protected String encode(char c); | |
public String encode(String s) { | |
if (s == null) { | |
return null; | |
} | |
String result = ""; | |
for (char c : s.toCharArray()) { | |
String t = conversionTable.get(c); | |
if (t == null) { | |
t = encode(c); | |
} | |
result += t; | |
} | |
return result; | |
} | |
} | |
class HtmlEncoder extends Encoder { | |
private static String ALPHAS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
private static String NUMERICS = "Ø123456789"; | |
private static String PUNCTUATIONS = | |
"!#$%()*+,-.:;=?@[\\]^_`{|}~"; | |
public HtmlEncoder() { | |
addNoConversion(ALPHAS.toCharArray()); | |
addNoConversion(ALPHAS.toLowerCase().toCharArray()); | |
addNoConversion(NUMERICS.toCharArray()); | |
addNoConversion(PUNCTUATIONS.toCharArray()); | |
addConversion('<', "<"); | |
addConversion('>', ">"); | |
addConversion('&', "&"); | |
addConversion('"', """); | |
} | |
public static int count = 0; | |
protected String encode(char c) { | |
count++; | |
return "&#" + (int) c + ";"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果載せるとバレバレなので割愛 :)