在網站使用input或textarea提供給用戶可輸入內容的功能,好比發帖子,發文章,發評論等等。這時候須要後端程序對輸入內容做安全過濾,好比<script>等可形成安全隱患的標籤。css
java中有個開源包叫Jsoup,自己用來解析html,xml文檔的,特色是能夠使用相似jquery的選擇權語法。html
最近在解決內容安全過濾的時候,經過google發現Jsoup經過自定義Whitelist(安全標籤白名單)提供了這樣的功能,很是好用。java
簡單演示以下:jquery
//HTML cleanString unsafe = "<table><tr><td>1</td></tr></table>" + "<img src='' alt='' />" + "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a>" + "<object></object>" + "<script>alert(1);</script>" + "</p>"; String safe = Jsoup.clean(unsafe, Whitelist.relaxed()); System.out.println("safe: " + safe);
官方API地址: http://jsoup.org/apidocs/org/jsoup/safety/Whitelist.html後端
發現來源:api
http://www.oschina.net/question/12_10232 , 據此本身寫了個自定義的幫助類:安全
package com.cssor.safety; import org.jsoup.Jsoup; import org.jsoup.helper.StringUtil; import org.jsoup.safety.Whitelist; public class ContentSafeFilter { private final static Whitelist user_content_filter = Whitelist.relaxed(); static { //增長可信標籤到白名單 user_content_filter.addTags("embed","object","param","span","div"); //增長可信屬性 user_content_filter.addAttributes(":all", "style", "class", "id", "name"); user_content_filter.addAttributes("object", "width", "height","classid","codebase"); user_content_filter.addAttributes("param", "name", "value"); user_content_filter.addAttributes("embed", "src","quality","width","height","allowFullScreen","allowScriptAccess","flashvars","name","type","pluginspage"); } /** * 對用戶輸入內容進行過濾 * @param html * @return */ public static String filter(String html) { if(StringUtil.isBlank(html)) return ""; return Jsoup.clean(html, user_content_filter); //return filterScriptAndStyle(html); } /** * 比較寬鬆的過濾,可是會過濾掉object,script, span,div等標籤,適用於富文本編輯器內容或其餘html內容 * @param html * @return */ public static String relaxed(String html) { return Jsoup.clean(html, Whitelist.relaxed()); } /** * 去掉全部標籤,返回純文字.適用於textarea,input * @param html * @return */ public static String pureText(String html) { return Jsoup.clean(html, Whitelist.none()); } /** * @param args */ public static void main(String[] args) { String unsafe = "<table><tr><td>1</td></tr></table>" + "<img src='' alt='' />" + "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a>" + "<object></object>" + "<script>alert(1);</script>" + "</p>"; String safe = ContentSafeFilter.filter(unsafe); System.out.println("safe: " + safe); } }
Jsoup不支持相對路徑圖片的過濾,好比<img src=」/1.png」 alt=」」 />會被去掉src屬性,想了個簡單的方法避免:編輯器
/** * 自定義對用戶輸入內容進行過濾的標籤 * @param html * @return */public static String filter(String html) { if(StringUtil.isBlank(html)) return ""; String baseUri = "http://baseuri"; return Jsoup.clean(html, baseUri, user_content_filter).replaceAll("src=\"http://baseuri", "src=\"");}
http://cssor.com/jsoup-whitelist-clean-html-for-user-content.html網站