使用Java 对HTML代码进行转码
- /**
- * 去除HTML字串中的控制字符及不可视字符
- *
- * @param str
- * HTML字串
- * @return 返回的字串
- */
- public static String escapeHTML(String str) {
- int length = str.length();
- int newLength = length;
- boolean someCharacterEscaped = false;
- for (int i = 0; i < length; i++) {
- char c = str.charAt(i);
- int cint = 0xffff & c;
- if (cint < 32)
- switch (c) {
- case 11:
- default:
- newLength--;
- someCharacterEscaped = true;
- break;
- case '\t':
- case '\n':
- case '\f':
- case '\r':
- break;
- }
- else
- switch (c) {
- case '"':
- newLength += 5;
- someCharacterEscaped = true;
- break;
- case '&':
- case '\'':
- newLength += 4;
- someCharacterEscaped = true;
- break;
- case '<':
- case '>':
- newLength += 3;
- someCharacterEscaped = true;
- break;
- }
- }
- if (!someCharacterEscaped)
- return str;
- StringBuffer sb = new StringBuffer(newLength);
- for (int i = 0; i < length; i++) {
- char c = str.charAt(i);
- int cint = 0xffff & c;
- if (cint < 32)
- switch (c) {
- case '\t':
- case '\n':
- case '\f':
- case '\r':
- sb.append(c);
- break;
- }
- else
- switch (c) {
- case '"':
- sb.append(""");
- break;
- case '\'':
- sb.append("'");
- break;
- case '&':
- sb.append("&");
- break;
- case '<':
- sb.append("<");
- break;
- case '>':
- sb.append(">");
- break;
- default:
- sb.append(c);
- break;
- }
- }
- return sb.toString();
- }
测试:
- @Test
- public void test_escapeHTML(){
- String input="<script>";
- System.out.println(ValueWidget.escapeHTML(input));
- }
运行结果:
<script>
对应的js方法:
- escape: function (a) {
- a = a ? a : '';
- return a.replace(/</g, "\x26lt;").replace(/>/g, "\x26gt;").replace("/\x26/g", "\x26amp;").replace(/"/g, "\x26quot;");
- },
- unescape: function (a) {
- a = a ? a : '';
- return a.replace(/</g,
- "\x3c").replace(/>/g, "\x3e").replace(/&/g, "\x26").replace(/"/g, '"');
- },