package com.yihu.jw.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by yeshijie on 2020/8/27. */ public class XssUtil { private static final String REGEX_SCRIPT = "]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 private static final String REGEX_STYLE = "]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 private static final String REGEX_HTML = "<[^>]+>"; // 定义HTML标签的正则表达式 // private static final String REGEX_SPACE = "\\s*|\t|\r|\n";// 定义空格回车换行符 /** * 过滤掉script标签 * * @param htmlStr * @return */ public static String delScriptTag(String htmlStr) { if (htmlStr == null) return null; Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 return htmlStr; } /** * 过滤掉style标签 * * @param htmlStr * @return */ public static String delStyleTag(String htmlStr) { if (htmlStr == null) return null; Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签*/ return htmlStr; } /** * @param htmlStr * @return 删除Html标签 */ public static String delHTMLTag(String htmlStr) { if (htmlStr == null) return null; Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 return htmlStr; // 返回文本字符串 } /** * 将html标签中的<>进行转义,如只有"<"或者">"则不进行转义 */ public static String escapeHtml(String htmlStr) { if (htmlStr == null) return null; Pattern p_script = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); while (m_script.find()) { String str = m_script.group(); String str_target = str.replaceAll("<", "<").replaceAll(">", ">"); htmlStr = htmlStr.replaceAll(str, str_target); } return htmlStr; } /** * 转义html标签 * * @param input * @return */ public static String cleanXss(String input) { if (input == null) return null; return escapeHtml(delStyleTag(delScriptTag(input))); } public static void main(String[] args) { System.out.println(cleanXss("<'script>")); } }