zoukankan      html  css  js  c++  java
  • mybatis 插入 含有美元符号($) 字符串 报 java.lang.IndexOutOfBoundsException: No group 2 的问题

      一:问题描述:

        在springboot-security框架生成BCryptPasswordEncoder()方法生成加密后的密码后,带有$符号,导致新增用户的时候插入不了,报(IndexOutOfBoundsException: No group 2)的错误!

      谷歌一下 java.lang.IndexOutOfBoundsException: No group  这个错误会发现是 String.replace方法出现反斜杠或美元符号$时会出现这个异常,

      二:出现问题的原因:

      MyBatis直接插入含有$符号的字符串是可以的!

      我在项目中自定义了一个mybatis的分页插件,所以实现了mybaits的Interceptor接口!在mybatis的实现类中,为了拼接sql字符串,调用了replace这个方法,如下:

     sql = sql.replaceFirst("\?", youString);
    

      以此来完成,数据库的sql语句拼写!把"insert into sys_user(id,created_time,modified_time,remark,login_name,password,status) values(?,?,?,?,?, ? ,?)";中的"?"替换成对应的实体对象值!

      由于通过BCryptPasswordEncoder().encode加密后的密码是:$2a$10$9zXJY.gYiv2A6ay0pAMLzONOLswRaHSrbb8VZWW7O7K5aPlvraOfq 这样的字符串!里面还有$符号,导致调用

    String.replace的方法时候 报错,因为含有特殊字符,replace无法替换。所以需要对字符串进行转义!可以自己写方法,也可以调用jdk(1.5以后)里面的方法

    java.util.regex包中的Matcher.quoteReplacement()来进行字符串的转义!

    三:解决的办法是:
    所以只需要把 替换的方法改成如下 就可以了!
    sql = sql.replaceFirst("\?", Matcher.quoteReplacement(youString));

      其中quoteReplacement方法的源码是源码是:

      

    public static String quoteReplacement(String s) {
            if ((s.indexOf('\') == -1) && (s.indexOf('$') == -1))
                return s;
            StringBuilder sb = new StringBuilder();
            for (int i=0; i<s.length(); i++) {
                char c = s.charAt(i);
                if (c == '\' || c == '$') {
                    sb.append('\');
                }
                sb.append(c);
            }
            return sb.toString();
        }
    

      




      

  • 相关阅读:
    HDU 1069 Monkey and Banana
    HDU 1029 Ignatius and the Princess IV
    HDU 1024 Max Sum Plus Plus
    Gym100923H Por Costel and the Match
    Codeforces 682C Alyona and the Tree
    Codeforces 449B Jzzhu and Cities
    Codeforces (ccpc-wannafly camp day2) L. Por Costel and the Semipalindromes
    Codeforces 598D (ccpc-wannafly camp day1) Igor In the Museum
    Codeforces 1167c(ccpc wannafly camp day1) News Distribution 并查集模板
    快乐数问题
  • 原文地址:https://www.cnblogs.com/luffyu/p/8075002.html
Copyright © 2011-2022 走看看