java後臺對前端輸入的特殊字元進行轉義
阿新 • • 發佈:2019-02-04
HTML:
常見的幫助類有2個:一個是spring的HtmlUtils,另外一個是apache.commons下的StringEscapeUtils
1 public static void testHtml(){ 2 String str = "<a href='http://www.qq.com'>QQ</a><script>"; 3 /** 4 * Spring的HtmlUtils進行轉義 5 */ 6 //<a href='http://www.qq.com'>QQ</a><script>7 System.out.println(org.springframework.web.util.HtmlUtils.htmlEscape(str)); 8 //<a href='http://www.qq.com'>QQ</a><script> 9 System.out.println(org.springframework.web.util.HtmlUtils.htmlEscapeDecimal(str)); 10 //<a href='http://www.qq.com'>QQ</a><script> 11 System.out.println(org.springframework.web.util.HtmlUtils.htmlEscapeHex(str)); 12 13 /** 14 * Spring的HtmlUtils進行還原 15 */ 16 //<a href='http://www.qq.com'>QQ</a><script> 17 System.out.println(org.springframework.web.util.HtmlUtils.htmlUnescape("<a href='http://www.qq.com'>QQ</a><script>"));18 //<a href='http://www.qq.com'>QQ</a><script> 19 System.out.println(org.springframework.web.util.HtmlUtils.htmlUnescape("<a href='http://www.qq.com'>QQ</a><script>")); 20 //<a href='http://www.qq.com'>QQ</a><script> 21 System.out.println(org.springframework.web.util.HtmlUtils.htmlUnescape("<a href='http://www.qq.com'>QQ</a><script>")); 22 23 /** 24 * apache的StringEscapeUtils進行轉義 25 */ 26 //<a href='http://www.qq.com'>QQ</a><script> 27 System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeHtml(str)); 28 29 /** 30 * apache的StringEscapeUtils進行還原 31 */ 32 //<a href='http://www.qq.com'>QQ</a><script> 33 System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeHtml("<a href='http://www.qq.com'>QQ</a><script>")); 34 }
JavaScript:
常見的幫助類有2個:一個是spring的JavaScriptUtils,另外一個是apache.commons下的StringEscapeUtils
1 public static void testJavascript(){ 2 String js = "<script type='text/javascript'>var a=10;alert(a);</script>"; 3 /** 4 * Spring的JavaScriptUtils進行轉義, 未提供還原的方法 5 */ 6 //\u003Cscript type=\'text\/javascript\'\u003Evar a=10;alert(a);\u003C\/script\u003E 7 System.out.println(org.springframework.web.util.JavaScriptUtils.javaScriptEscape(js)); 8 9 /** 10 * apache的StringEscapeUtils進行轉義 11 */ 12 //<script type=\'text\/javascript\'>var a=10;alert(a);<\/script> 13 System.out.println(org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(js)); 14 /** 15 * apache的StringEscapeUtils進行還原 16 */ 17 //<script type='text/javascript'>var a=10;alert(a);</script> 18 System.out.println(org.apache.commons.lang.StringEscapeUtils.unescapeJavaScript(org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(js))); 19 }
SQL:
apache.commons下的StringEscapeUtils
/** * apache的StringEscapeUtils進行轉義 */ String sql = "select * from table where username='" + org.apache.commons.lang.StringEscapeUtils.escapeSql("admin' or '1=1") + "' and password='admin'"; //select * from table where username='admin'' or ''1=1' and password='admin' System.out.println(sql);