SpringBoot整合Shiro框架,遇到的反射以及密码加盐问题踩坑
记录一下
1.反射获取对象时,报NullPointerException空指针异常
- 在使用反射获取时,使用newInstance 方法获取对象时,报空指针,百度诸多方法未寻得一正确方法,后来在各种尝试便览下发现没获取超类参数的实际类型,加上之后解决了
try {
//Class a = Class.forName("com.zhouyou.sb.entity.UserInfo");
//UserInfo b = (UserInfo)a.newInstance();
//Field field = a.getDeclaredField(fieldName);
//获得超类的泛型参数的实际类型 否则报空指针异常
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
T model = modelClass.newInstance();
Field field = modelClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(model, value);
return mapper.selectOne(model);
} catch (ReflectiveOperationException e) {
throw new ServiceException(e.getMessage(), e);
}
2.shiro登录校验密码以及加盐处理:
/**
* 告诉shiro如何根据获取到的用户信息中的密码和盐值来校验密码
*/
{
//设置用于匹配密码的CredentialsMatcher
HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher();
hashMatcher.setHashAlgorithmName("md5");
hashMatcher.setStoredCredentialsHexEncoded(true);
//加密的次数
hashMatcher.setHashIterations(1);
this.setCredentialsMatcher(hashMatcher);
}
- 在此处配置md5加密次数以及转为16进制后,自定义1次在网站加密无法成功,后寻得博主的帮助成功解决。在此感谢 附上gitee地址:https://gitee.com/beany/mySpringBoot.git
public static void main(String []ages ) throws IllegalAccessException, InstantiationException {
//加密方式
String hashAlgorithmName = "md5";
//原密码
String credentials = "123456";
//加密次数
int hashIterations = 64;
//加密盐值,大家可以用生成字符串的方法
String hash = "wxKYXuTPST5SG0jMQzVPsg==";
ByteSource credentialsSalt = ByteSource.Util.bytes(hash);
String password = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
System.out.println(password);
}
ps: 才疏学浅,相互学习,如有不足之处,望指正