一、前言
关于spring-web(4.1.4)的org.springframework.web.util.JavaScriptUtils工具类对于转义特殊字符显示到前端javascript代码,需要进行反斜杠\等处理,工具类具体代码如下所示
二、源码说明
package org.springframework.web.util;@b@@b@public class JavaScriptUtils@b@{@b@ public static String javaScriptEscape(String input)@b@ {@b@ if (input == null) {@b@ return input;@b@ }@b@@b@ StringBuilder filtered = new StringBuilder(input.length());@b@ char prevChar = ';@b@@b@ for (int i = 0; i < input.length(); ++i) {@b@ char c = input.charAt(i);@b@ if (c == '"') {@b@ filtered.append("\\\"");@b@ }@b@ else if (c == '\'') {@b@ filtered.append("\\'");@b@ }@b@ else if (c == '\\') {@b@ filtered.append("\\\\");@b@ }@b@ else if (c == '/') {@b@ filtered.append("\\/");@b@ }@b@ else if (c == '\t') {@b@ filtered.append("\\t");@b@ }@b@ else if (c == '\n') {@b@ if (prevChar != '\r')@b@ filtered.append("\\n");@b@@b@ }@b@ else if (c == '\r') {@b@ filtered.append("\\n");@b@ }@b@ else if (c == '\f') {@b@ filtered.append("\\f");@b@ }@b@ else if (c == '\b') {@b@ filtered.append("\\b");@b@ }@b@ else if (c == '\11') {@b@ filtered.append("\\v");@b@ }@b@ else if (c == '<') {@b@ filtered.append("\\u003C");@b@ }@b@ else if (c == '>') {@b@ filtered.append("\\u003E");@b@ }@b@ else if (c == 8232) {@b@ filtered.append("\\u2028");@b@ }@b@ else if (c == 8233) {@b@ filtered.append("\\u2029");@b@ }@b@ else@b@ filtered.append(c);@b@@b@ prevChar = c;@b@ }@b@@b@ return filtered.toString();@b@ }@b@}