防止SQL注入的方法(エスケープ処理)

2022/2/1 19:09:53

本文主要是介绍防止SQL注入的方法(エスケープ処理),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

エスケープとは、HTML上で特殊文字を期待通りに表示するために施す処理のことです
指定された文字列中に存在する SQL 上特別な意味を持つ文字をエスケープします.

package exam;

import com.sun.deploy.util.StringUtils;

public class Test4 {
    public static void main(String[] args) {
        String target = "%a\\bc_defgh";
        if (target == null) {
            throw new IllegalArgumentException("Target argument is null.");
        }//方式sql注入
        //エスケープとは、HTML上で特殊文字を期待通りに表示するために施す処理のことです
        //指定された文字列中に存在する SQL 上特別な意味を持つ文字をエスケープします.<br>
        target = StringUtil.replace(target, "\\", "\\\\");
        target = StringUtil.replace(target, "'", "''");
        target = StringUtil.replace(target, "%", "\\%");
        target = StringUtil.replace(target, "_", "\\_");
        target = StringUtil.replace(target, "%", "\\%");
        target = StringUtil.replace(target, "a", "b");
        String replace = StringUtil.replace(target, "_", "\\_");
        System.out.println("replace = " + replace);
    }
}

class StringUtil {
    public static String replace(String target, String replaceFrom, String replaceTo) {
        if (target == null) {
            throw new IllegalArgumentException("Target argument is null.");
        }
        if (replaceFrom == null) {
            throw new IllegalArgumentException("ReplaceFrom argument is null.");
        }
        if (replaceFrom.length() == 0 || replaceTo == null) {
            return target;
        }

        int begin;
        int end;

        String checking = new String(target);
        StringBuffer buffer = new StringBuffer();

        while (checking.length() != 0) {
            // 文字列中に置き換え対象文字列がないかどうかを調べる
            begin = checking.indexOf(replaceFrom);
            if (begin == -1) {
                // 文字列中に置き換え対象文字列が見つからなかった
                // ので、残りの文字列には置き換えは必要ない
                buffer.append(checking);
                break;
            } else {
                // 文字列中に置き換え対象文字列が見つかったので
                // 置き換え終了位置を求める
                end = begin + replaceFrom.length();
                buffer.append(checking.substring(0, begin));
                // 置き換え後文字列を置き換え対象文字列のかわりに使う
                buffer.append(replaceTo);
                checking = checking.substring(end);
            }
        }

        return buffer.toString();
    }
}

在这里插入图片描述



这篇关于防止SQL注入的方法(エスケープ処理)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程