java 防止 XSS 攻击的常用方法总结

来源:互联网 发布:飞机部件修理就业数据 编辑:程序博客网 时间:2024/04/30 03:38

参考文章:

http://ju.outofmemory.cn/entry/54043

http://www.yihaomen.com/article/java/409.htm

import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang.StringUtils;import org.springframework.util.AntPathMatcher;import org.springframework.util.PathMatcher;import org.springframework.web.filter.OncePerRequestFilter;import com.geekymv.utils.PreviewTextUtils;import com.geekymv.wrapper.XSSRequestWrapper;public class XSSFilter extends OncePerRequestFilter {private PathMatcher matcher = new AntPathMatcher();  /** * 不过滤的url */private List<String> excludeUrls = new ArrayList<String>();/** * 不过滤的参数 */private List<String> excludeParams = new ArrayList<String>();public void setExcludeUrls(String excludeUrls) {if(StringUtils.isNotBlank(excludeUrls)) {String[] exStrings =  excludeUrls.split(",");if(exStrings == null || exStrings.length == 0) {return;}for (String uri : exStrings) {this.excludeUrls.add(PreviewTextUtils.replaceBlank(uri));}}}public void setExcludeParams(String excludeParams) {if(StringUtils.isNotBlank(excludeParams)) {String[] exStrings = excludeParams.split(",");if(exStrings == null || exStrings.length == 0) {return;}for (String param : exStrings) {this.excludeParams.add(PreviewTextUtils.replaceBlank(param));}}}@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String uri = request.getRequestURI();String contextPath = request.getContextPath();if(StringUtils.isNotBlank(uri) && StringUtils.isNotBlank(contextPath)) {int length = contextPath.length();uri = uri.substring(length);}boolean flag = false;for (String  excludeUrl: excludeUrls) {if(matcher.match(excludeUrl, uri)) {flag = true;break;}}if(flag) {filterChain.doFilter(request, response);}else {// 获取不包含的参数List<String> paramNames = new ArrayList<String>();for (String param : excludeParams) {String[] values = param.split(":"); // /aaa/test:(content|desc)String exUri = values[0];if(matcher.match(exUri, uri)) {String params = values[1]; // (content|desc)paramNames = Arrays.asList(params.substring(1, params.length()-1).split("\\|"));break;}}if(paramNames != null && !paramNames.isEmpty()) {// 有不需要过滤的参数filterChain.doFilter(new XSSRequestWrapper(request, paramNames), response);}else {filterChain.doFilter(new XSSRequestWrapper(request), response);}}}}


0 0
原创粉丝点击