声明本文只适合初学者,本人也是刚接触而已,通过一段时间的研究小有收获,特来分享下但愿和你们互相交流学习。
首先配置咱们的web.xml代码以下:
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
}
各部分代码功能上面注释已基本解释了,我要说的是,咱们平时有可能比较喜欢使用currUser对象,可是貌似在这里没有办法获得了。其实否则,首先shiro给咱们提供的Subject的会话能够知足咱们的需求
Session session = subject.getSession();
Session session = subject.getSession(boolean create);
这些方法在概念上等同于HttpServletRequest API。第一个方法会返 回Subject的现有会话,或者若是尚未会话,它会建立一个新的并将之返回。
第二个方法接受一个布尔参数,这个参数用于断定会话不存在时是否建立新会话 。一旦得到Shiro的会话,你几乎能够像使用HttpSession同样使用它。Shiro团 队以为对于Java开发者,HttpSession API用起来太舒服了,因此咱们保留了它 的不少感受。固然,最大的不一样在于,你能够在任何应用中使用Shiro会话,不 仅限于Web应用。 所以你能够再验证登录里写这样的一句话来完成咱们的代码转换 SecurityUtils.getSubject().getSession().setAttribute("currUser", user); 注意在异常处理里须要移除此currUser。 固然官方推荐使用 Subject
最后就是咱们的Controller了。 在这里我介绍登录和退出
@RequestMapping("/user/login")
@RequestMapping("/user/exit")
好了,这样基本算是完成任务了,接下来就是页面上的操做了。为此shiro还提供了相应的标签,在这里我就照搬官方的了,由于这个实在简单,你们一看就明白
引用 <%@
验证当前用户是否为“访客”,即未认证(包含未记住)的用户
- <shiro:guest>
-
Hi there! Please <a href="login.jsp">Login</a> or <ahref="signup.jsp">Signup</a> today! - </shiro:guest>
user标签
认证经过或已记住的用户
- <shiro:user>
-
Welcome back John! Not John? Click <a href="login.jsp">here<a> to login. - </shiro:user>
authenticated标签
已认证经过的用户。不包含已记住的用户,这是与user标签的区别所在。
- <shiro:authenticated>
-
<a href="updateAccount.jsp">Update your </a>.contact information - </shiro:authenticated>
notAuthenticated标签
未认证经过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。
- <shiro:notAuthenticated>
-
Please <a href="login.jsp">login</a> in order to update your credit card information. - </shiro:notAuthenticated>
principal 标签
输出当前用户信息,一般为登陆账号信息
- Hello,
<shiro:principal/>, how are you today?
hasRole标签
验证当前用户是否属于该角色
- <shiro:hasRole
name="administrator"> -
<a href="admin.jsp">Administer the </a>system - </shiro:hasRole>
lacksRole标签
与hasRole标签逻辑相反,当用户不属于该角色时验证经过
- <shiro:lacksRole
name="administrator"> -
Sorry, you are not allowed to administer the system. - </shiro:lacksRole>
hasAnyRole标签
验证当前用户是否属于如下任意一个角色。
- <shiro:hasAnyRoles
name="developer, project >manager, administrator" -
You are either a developer, project manager, or administrator. - </shiro:lacksRole>
hasPermission标签
验证当前用户是否拥有制定权限
- <shiro:hasPermission
name="user:create"> -
<a href="createUser.jsp">Create a </a>new User - </shiro:hasPermission>
lacksPermission标签
与hasPermission标签逻辑相反,当前用户没有制定权限时,验证经过
Xml代码
- <shiro:hasPermission
name="user:create"> -
<a href="createUser.jsp">Create a </a>new User - </shiro:hasPermission>

user == subject:用户, group(role):角色
permission:权限(拥有权限比较细的状况,通常只要user和group就知足要求了)
最后 提一下jar包,别弄错了。是shiro-all.jar。能够从官网下载 http://shiro.apache.org/download.html