之前也提到过使用org.apache.commons.lang.StringEscapeUtils这个工具类对用户提交的数据转义,但是这样做不够好,万一哪天程序有什么改动,或者另一个需要使用这些数据的开发人员在数据输出的时候又转义了一下呢?最直接的应该是将提交的数据中的XSS过滤掉,只存储正常数据,这种需求交给owaspantisamy就行了。

第一步
从http://code.google.com/p/owaspantisamy/downloads/list下载如下文件(版本当然找最新的了):
antisamy-1.4.4.jar
antisamy-required-libs-1.2.zip
antisamy-slashdot.xml
第二步
将antisamy-required-libs-1.2.zip中的jar连同antisamy-1.4.4.jar一起放入WEB-INF/lib下,antisamy-slashdot.xml放入WEB-INF下。
接下来写一个测试页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" import="org.owasp.validator.html.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>防XSS测试</title>
</head>
<body>
<%
    String content = request.getParameter("content");
    if(null != content && !"".equals(content)){
        Policy policy = Policy.getInstance(request.getRealPath("WEB-INF/antisamy-slashdot.xml"));
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(content, policy);
        out.print(cr.getCleanHTML());
        %><hr />www.ineeke.com<%
    }else{
        %>
            <form action="" method="post">
            <input name="content" type="text" />
            <input type="submit" />
            </form>
        <%
    }
%>
</body>
</html>

测试了一下,效果不错!对各种变形XSS也能过滤掉。

除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。 转载原创文章请注明,转载自:Neeke[http://www.ineeke.com] 本文链接: http://www.ineeke.com/archives/1403/