
1.创建一个oc的项目通过cocoapods管理方式引入realm ( pod 'Realm', '~>10.5.0').
2.打开项目,演示realm简单的增、删、改、查用法。
1.创建一个 Realm 的模型
注意:对象必须继承 RLMObject
注意:后面需要演示到查询和删除,所以这里多添加几条李四,王五,赵六,孙七、周八、吴九、郑十的信息
Realm其它用法:
iOS - objective-c中realm的对应关系
iOS - objective-c中realm的迁移
pricipal是一个Object,就是我们的带有username属性的实体对象
详细解释如下:
在登录的方法中,调用了subject.login(token)后,还要手动利用principal和realmName构造SimpleAuthenticationInfo对象,其实这里的pricipal是一个Object,就是我们的带有username属性的实体对象,然后将SimpleAuthenticationInfo对象存放在session中。
代码如下:
try {subject.login(token)
//获取realmSecurityManager对象,其包含了很多信息,比如配置文件里面的数据
RealmSecurityManager realmSecurityManager = (RealmSecurityManager) securityManager
Collection<Realm> collection = realmSecurityManager.getRealms() if (collection!=null && collection.size()>0){
Iterator iterator = collection.iterator()
while (iterator.hasNext()){
Realm realm = (Realm)iterator.next()
//得到默认的数据源名称,虽然默认的为iniRealm,也可以通过程序获得
String realmName = realm.getName()
//自定义的实体对象
User user = new User()
user.setUsername(username)
user.setPassword(password)
//得到SimpleAuthenticationInfo对象
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,realmName) //通过源码分析在调用subject.login(token)后,会通过SubjectContext来保存到session,所以就直接复用了源码(DefaultSecurityManager类中)
SubjectContext subjectContext = new DefaultSubjectContext()
subjectContext.setAuthenticated(true)
subjectContext.setAuthenticationToken(token)
subjectContext.setAuthenticationInfo(info)
if (subject != null) {
subjectContext.setSubject(subject)
} //此方法中进行保存
realmSecurityManager.createSubject(subjectContext)
}
}
}catch (UnknownAccountException e){
error = "用户名不存在"
}catch (IncorrectCredentialsException e){
error = "用户名或密码错误"
}catch (AuthenticationException e){
error = "其他错误"+e.getMessage()
}
最后结果是在页面上标签<shiro:principal property="username" />能正确显示结果,说明此方法可行。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)