java后台对前端输入的特殊字符进行转义
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);