
在页面上使用shiro标签的时候,会自动触发MyShiroRealm类中的用户授权方法doGetAuthorizationInfo,即在加载页面的时候,如果发现页面上有使用shiro标签(不是引入标签库的时候),那么,会返回回去先执行doGetAuthorizationInfo方法,执行完,再返回页面。
导入标签库
guest标签
<shiro:guest>
欢迎游客访问,<ahref="${pageContext.request.contextPath}/login.jsp">登录</a>
</shiro:guest>
用户没有身份验证时显示相应信息,即游客访问信息。jsp标签大全
user标签
<shiro:user>
欢迎[<shiro:principal/>]登录,<ahref="${pageContext.request.contextPath}/logout">退出</a>
</shiro:user>
用户已经身份验证/记住我登录后显示相应的信息。
authenticated标签
<shiro:authenticated>
用户[<shiro:principal/>]已身份验证通过
</shiro:authenticated>
用户已经身份验证通过,即Subject.login登录成功,不是记住我登录的。

流程分析:
<shiro:principal property="username" />这种写法,是要把一个带有username属性的对象转换为Prinipal后保存在session中,才能在页面上正确显示结果的。由于开始学习,所以我用的是ini配置文件作为安全数据源的。在登录的方法中,调用了subject.login(token)后,还要手动利用principal和realmName构造SimpleAuthenticationInfo对象,其实这里的pricipal是一个Object,就是我们的带有username属性的实体对象,然后将SimpleAuthenticationInfo对象存放在session中。
代码如下:
try {
subject.login(token);
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();
String realmName = realm.getName();
User user = new User();
user.setUsername(username);
user.setPassword(password);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,realmName);
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();
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-64011-1.html
估计更差