java web 防止xss注入

Java web中如何防止xss 注入呢?

首先讨论第一个问题:存到数据库中的是转码之后的还是转码之前的?

转码之后:

转码之前:

 

结论是:存到数据库中的就是转码之前的.为什么呢?

因为xss 攻击只存在PC web端,如果数据库中存储的就是转码之后的,那么手机app显示出来不就有问题了么?

 

所以最终的做法就是在PC web端 转码:

转码方法:

escape= function (str) {
            str = str ? str : '';
            return str.replace(/</g, "\x26lt;").replace(/>/g, "\x26gt;").replace("/\x26/g", "\x26amp;").replace(/"/g, "\x26quot;");
        };

        unescape= function (str) {
            str = str ? str : '';
            return str.replace(/&lt;/g,
                "\x3c").replace(/&gt;/g, "\x3e").replace(/&amp;/g, "\x26").replace(/&quot;/g, '"');
        };

 

注意:

在Java 后台也不要转码,只在PC web端转码,而且只在显示用户输入的字段时转码

 

 

 实际案例

用户名中包含单引号就报错:



 按道理, <#escape x as x?html>就是用于解决xss攻击的,

可以把单引号转化为:&apos;

可是没有!!!

解决方法:

在服务器端对单引号进行转义:

public static String escapeUserName(String name){
        return name.replace("'", "\\'");
    }

 

 

 这就是<#escapex as x?html>的坑

 

 

 

 

 

猜你喜欢

转载自hw1287789687.iteye.com/blog/2238307