jsp解決XSS攻擊的方案:
1.采用struts2的攔截器過濾,將提交上來的參數轉碼來解決,例如配置struts.xml,代碼如下:
<package name="default" namespace="/"
extends="struts-default, json-default">
<!-- 配置攔截器 -->
<interceptors>
<!-- 定義xss攔截器 -->
<interceptor name="xssInterceptor" class="...此處填寫攔截器類名"></interceptor>
<!-- 定義一個包含xss攔截的攔截棧 -->
<interceptor-stack name="myDefault">
<interceptor-ref name="xssInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 這個必須配置,否則攔截器不生效 -->
<default-interceptor-ref name="myDefault"></default-interceptor-ref>
<action>
...此處省略n個action
</action>
</package>
2.使用Java代碼,攔截器實現類,例如:
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class XssInterceptor extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
ActionContext actionContext = invocation.getInvocationContext();
Map<String, Object> map = actionContext.getParameters();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String value = ((String[])(entry.getValue()))[0];
entry.setValue(StringEscapeUtils.escapeHtml4(value));//將提交上來的字符串進行轉碼
//System.out.println((entry.getValue()));
}
return invocation.invoke();
}
}