防止数据库条目 ID 直接暴露给前端用户, 传给前端时在dto上转成混淆后的string, 后端接收时由混淆后的string转成long, 其余逻辑不变.
package tech.houxi.learning.service;
public class Main {
private static final String alphabet = "zFOsDRcPWunIhk01y9Xe6fwSjrgp2HNb5di4QMUaB8CY73EAKZlomqVTGxtJvL";
public static void main(String[] args) throws Exception {
long id = 1133;
System.out.println("id = " + id);
String strId = toId(id);
System.out.println("strId = " + strId);
long longId = toLong(strId);
System.out.println("longId = " + longId);
}
// long转str
public static String toId(Long id) {
if (id == null) {
return "";
}
if (id < 0) {
throw new RuntimeException("id必须大于等于0");
}
StringBuilder sb = new StringBuilder();
do {
int i = (int) (id % alphabet.length());
sb.append(alphabet.charAt(i));
id /= alphabet.length();
} while (id > 0);
return sb.toString();
}
// str转long
public static Long toLong(String id) {
if (id == null || id.length() == 0) {
return null;
}
int length = alphabet.length();
long num = 0;
for (int i = id.length() - 1; i >= 0; i--) {
int indexOf = alphabet.indexOf(id.charAt(i));
if (indexOf == -1) {
throw new RuntimeException("id错误");
}
num = num * length + indexOf;
}
return num;
}
}
输出
#示例一:
id = 1133
strId = 9X
longId = 1133
示例二:
id = 344333
strId = A4pF
longId = 344333